jQuery on submit for a form not activating, when jQuery loads the form -
i have puzzling error.
i loading html file div, contains form, jquery .on(‘submit’) not work.
if don’t load html div , instead have in original file, ".on('submit') works. can not see difference.
using google chrome on mac view script
the reason loading file, have different forms, depending on using script.
is timing error or execution order have messed ?
html , js
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> </head> <body> <div id="divheader"> <form id="frmlookup" method="post"> <table id="tblhdr"> <tr> <td><img id="logo" src="logo120.jpg" /></td> <td> <input id="inphdr" type="text" name="qrywords" size="23" placeholder="your search word/s, number/s" onfocus="this.placeholder = ''" onblur="this.placeholder = 'your search word/s, number/s'" /> </td> <td> <button id="btnhdrfind" type="submit" value=" find trees " name="find" > find<br>trees </button> </td> <td> <span id="hdrname">my site</span> </td> <td> <button type="button" class="btnhdr" name="help" onclick="togglehelp();" >help<br>?</button> </td> </tr> </table> </form> </div> <div id="divresults"></div> <script> // ********************** when on submit not work ???????????????? //$( "#divheader" ).load( "sheader.html", function() { //}); $("#frmlookup").on('submit', function(e) { e.preventdefault(); alert("submitting"); getdata("data"); }); function getdata(frm) { alert("processing form , call ajax results"); return; } </script>
the file load
<form id="frmlookup" method="post"> <table id="tblhdr"> <tr> <td><img id="logo" src="logo120.jpg" /></td> <td> <input id="inphdr" type="text" name="qrywords" size="23" placeholder="your search word/s, number/s" onfocus="this.placeholder = ''" onblur="this.placeholder = 'your search word/s, number/s'" /> </td> <td> <button id="btnhdrfind" type="submit" value=" find trees " name="find" > find<br>trees </button> </td> <td> <span id="hdrname">trees in arboretum</span> </td> <td> <button type="button" class="btnhdr" name="help" onclick="togglehelp();" >help<br>?</button> </td> </tr> </table> </form>
your problem jquery's .load()
function asynchronous.
while jquery loading file, moves on , registers event handler (on html isn't loaded yet), renders file, , therefore event handler not trigger.
try either
a) put event handler in callback function of .load()
so:
$( "#divheader" ).load( "sheader.html", function() { $("#frmlookup").on('submit', function(e) { e.preventdefault(); alert("submitting"); getdata("data"); }); });
or
b) use event delegation so:
$( "#divheader" ).load( "sheader.html", function() {}); $(document).on('submit', "#frmlookup", function(e) { e.preventdefault(); alert("submitting"); getdata("data"); });
also, worth mentioning jquery code should inside of document ready function.
$(function () { // code goes here });
Comments
Post a Comment