Frank Lucas Frank Lucas - 3 months ago 19
HTML Question

preventDefault form submit not working in bootstrap popover

I have a bootstrap popover element with a form inside. I do a preventDefault when the form is submitted but it doesn't actualy prevent the submit.

When I don't use the popover and a modal instead it works perfectly.

Here is my HTML:

<div id="popover-content" class="hide">
<form action="api/check.php" id="requestacallform" method="GET" name="requestacallform" class="checkform">
<div class="form-group">
<div class="input-group">
<input id="domein" type="text" class="form-control" placeholder="domein" name="name"/>
</div>
</div>
<input type="submit" value="Aanmelden" class="btn btn-blue submit" />
<p class="response"></p>
</form>
</div>


Here is my javascript file where I create the popup (main.js)

$('#popover').popover({
html : true,
content: function() {
return $("#popover-content").html();
}
});


And this is where I do my preventDefault in an other javascript file

$(".checkform").submit(function(e){
e.preventDefault();
var request = $("#domein").val();
$.ajax({
...
});


Anyone knows why the preventDefault isn't working?

Any help is greatly appreciated!

Many thanks in advance!!

Answer

You're trying to append event handler for .checkform before adding it to DOM. You need to load second javascript file after loading contents html or append event globaly:

$("body").on("submit",".checkform", function(e){
    e.preventDefault();
    var request = $("#domein").val();
    $.ajax({
       ...
});

You can read more about events binding on dynamic htmls here