4

I have a form where a button included, when button is clicked the form is submitted, and how to prevent this. for example I just want to show a "alert" when the button is clicked. and put the button outside of form is not a option for me.

and BTW I use bootstrap framework.

    <form class="form-inline" role="form" id="form-area">
        <input type="hidden" name="key" value="dept-area">
        <div class="form-group">
            <input type="text" class="form-control" name="data" placeholder="">
        </div>

        <button class="btn btn-default" id="btn-area">test</button>
    </form>
jgillich
  • 63,850
  • 5
  • 53
  • 80
sureone
  • 801
  • 2
  • 13
  • 23

4 Answers4

5

I don't agree with the javascript answers. They work, but they're not fixing the cause of the problem.

The form is being submitted because the <button> element has a type of submit by default (see the spec here).

You can get around this by putting type="button" in the html like so:

 <button type="button" class="btn btn-default" id="btn-area">
Timothy Jones
  • 20,787
  • 6
  • 56
  • 89
2

Use event.preventDefault();

clicked anchors will not take the browser to a new URL. We can use event.isDefaultPrevented() to determine if this method has been called by an event handler that was triggered by this event.

 $("#btn-area").click( function(event) {


 event.preventDefault();

     alert("hello ");

}); 

http://jsfiddle.net/BL3Jk/

Mr7-itsurdeveloper
  • 1,611
  • 1
  • 17
  • 23
0

You can try this:

$('#form-area').submit(function (event) {
    event.preventDefault();
});
Joe
  • 103
  • 1
  • 7
0

You Can use jquery like this

$("#btn-area").click(function(event){
alert("Your alert");
event.preventDefault();
});