I have two HTML forms. First one is searchForm and second one is searchFormSPECIAL.
The difference is that searchForm gets printed initially in the HTML, while searchFormSPECIAL is appended by jQuery when user click button oooo.
I also set up two submit listeners $(“#searchForm”).submit(function(event) and $(“#searchFormSpecial”).submit(function(event). First one is working, second one is not.
Here is my code:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$("#test_only").click(function () {
$('body').append(commentFormSPECIAL());
});
function commentFormSPECIAL() {
var comment_form_html = '<form action="/comment" id="searchFormSPECIAL">\
<input type="text" name="r" placeholder="Topic ID" />\
<input type="text" name="c" placeholder="Comment ..." />\
<input type="submit" value="Submit Comment" />\
</form>'
return comment_form_html;
//return "";
}
$("#searchForm").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
alert("Hey you are submitting searchForm")
});
$('#searchFormSPECIAL').submit(function(event){
/* stop form from submitting normally */
event.preventDefault();
alert("Hey you are submitting searchFormSPECIAL");
});
</script>
</head>
<body>
<div id="wrapper">
<form action="/new" id="searchForm">
<input type="text" name="s" placeholder="Topic..." />
<input type="text" name="l" placeholder="http://www.google.com" />
<input type="submit" value="Submit Topic" />
</form>
<button id="test_only">ooooo</button>
</div>
</body>
</html>
It seems that jQuery is not recognizing appended form.
Thanks in advance!
You should bind the click event when the DOM hierarchy has been fully constructed by the browser.
Try to put your code in $(document).ready