Stiño
Stiño

Reputation: 2853

How to select a button inside a form tag with javascript?

I am trying to make a confirmation message popup when submitting a form using the bootbox plugin. The problem is that I don't know how to select the button inside the form tag. In the example below the confirmation message does work for the button outside the form tag but not for the one inside. How do I select this button wrapped inside the form tag?

<div class="bs-example">
<div class="col-md-4 col-md-offset-4">
<form action="#" method="POST">
    <div class="form-group">
        <input type="username" class="form-control" id="inputEmail" placeholder="Username">
    </div>
    <div class="form-group">
        <input type="email" class="form-control" id="inputEmail" placeholder="Email">
    </div>
    <div class="form-group">
        <input type="password" class="form-control" id="inputPassword" placeholder="Password">
    </div>
    <div class="form-group">
        <input type="password" class="form-control" id="inputPassword" placeholder="Repeat password">
    </div>  
    <div class="checkbox">
        <label><input type="checkbox"> Remember me</label>
    </div>
            <button class='btn btn-signup btn-signup-sm' type="submit">Sign up</button>
</form>
</div>
</div>

<button class='btn btn-signup btn-signup-sm' type="submit">Sign up</button>

<script type="text/javascript">
$(document).ready(function(){
$('.btn').on('click', function(){
    bootbox.alert("hello there");
});
});
</script

Upvotes: 0

Views: 1455

Answers (2)

ray9209
ray9209

Reputation: 388

Change javascript code to:

<script type="text/javascript">
$(document).ready(function(){
$('.btn').on('click', function(e){
    e.preventDefault();          // this line is key to preventing page reload
                                 // when user clicks submit button inside form
    bootbox.alert("hello there");
});
});
</script>

Upvotes: 1

Giannis Grivas
Giannis Grivas

Reputation: 3412

Why don't you catch the submit event of the form?

Give your form an id like "<form method="POST" id="my_form">...</form>"

and use:

$('#my_form').submit(function(){
   bootbox.alert("hello there");
});

Take a look at your fiddle here!

Upvotes: 1

Related Questions