Reputation:
What would be the best way to handle the submit event when you have multiple forms dynamically created with the same form id in jQuery?
So far this line makes that jQuery only handles the first form.
$("form#noteform").submit(function(){
// do stuff
});
Kind of confusing, because I really need to catch the submit of a particular form to get the correct post values, therefore the selector of the form must be unique.
How can you make it listen to all submits and later identify if it is the correct form id that launched the submit?
Upvotes: 0
Views: 6232
Reputation: 17548
I've complete reworked my answer... It's cleaner, simpler, and it works for dynamically added forms too! ;-P
<script language="javascript">
$(function() {
$('form').live('specialSubmit',function() {
// do stuff... the form = $(this)
alert($(this).serialize()); // to prove it's working...
});
bind_same_id_forms('noteform');
});
function bind_same_id_forms(id) {
$('form').die().live('keypress',function(ev) {
if(ev.keyCode == 13 && $(this).attr('id') == id) {
$(this).trigger('specialSubmit');
return false;
}
}).children(':submit,:image').die().live('click',function(ev) {
if($(this).attr('id') == id) {
$(this).trigger('specialSubmit');
return false;
}
});
}
</script>
Example HTML:
<form id="noteform" action="question/save/1234" method="post">
<input type="text" name="question" />
<input type="text" name="answer" />
<input type="submit"value="Save" />
</form>
<!-- more forms -->
<form id="noteform" action="question/save/4321" method="post">
<input type="text" name="question" />
<input type="text" name="answer" />
<input type="submit" value="Save" />
</form>
Upvotes: 0
Reputation: 3287
What would be the best way to handle the submit event when you have multiple forms dynamicly created with the same form id in jQuery?
If id is 'noteform', to select all form with that id:
jQuery('form[id="noteform"]')
Caution: It may not be the best idea to have multiple HTML element (including form) to have non-unique id.
How can you make it listen to all submits?
You may bind event on its event:
jQuery('form[id="noteform"]').submit(function(e){});
and later identify, if it is the correct form id that launched the submit?
Although by using the selector, it is guaranteed (in my opinion) to have form with correct id, you can check the id of the form in the submit event, by using this object, eg:
jQuery('form[id="noteform"]').submit(function(e){
if(this.id=='noteform') {/* do interesting stuffs */}
// use .index function to determine the form index from the jQuery array.
alert('index='+jQuery('form[id="noteform"]').index(this));
});
If you are interested in POC code snippet that I use to test them (solution), here it is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled 1</title>
<script type="text/javascript" src="jquery-1.3.2.js"></script>
</head>
<body>
<form id="noteform"><div>
<input type="submit" value="submit" />
</div></form>
<form id="noteform"><div>
<input type="submit" value="submit" />
</div></form>
<form id="noteform"><div>
<input type="submit" value="submit" />
</div></form>
<script type="text/javascript">
/* <![CDATA[ */
// test for selection
jQuery('form[id="noteform"]').each(function(i){
alert('noteform #' + i); //
});
// test for submission
jQuery('form[id="noteform"]').submit(function(e){
if(this.id=='noteform'){
alert('index='+jQuery('form[id="noteform"]').index(this));
return false; // cancel submission
}
});
/* ]]> */
</script>
</body>
</html>
Thanks.
Upvotes: 0
Reputation: 4769
There is no best way to do this using ID's, because having multiple elements with the same ID is invalid HTML.
I would suggest instead your forms have unique ID's but share a class name. If you then needed to get the first one, you could use the ID directly or the class and the jquery :first selector.
$('form.className:first').submit(function(){
stuff();
});
-edit- Trying to actually address the issue of identifying which form has been submitted. Again this solution relies on Unique form ID's
$('form.className').submit(function(){
switch( $(this).attr('id') ){
case 'form1id':
submitForm1();
break;
case 'form2id':
submitForm2();
break;
default:
stuff()
break;
}
});
Upvotes: 4
Reputation:
I revised my code example of creating a new note
This one attaches the submit event too the newly added form within the callback function off the load event.
It's a step forward because the other examples diddn't do the job, for some reason.
I don't know about any drawbacks off doing it like this, yet!! I am open for any comments on the issue If you want see example
Purpose&Comments: The newnote function takes two arguments
-: index = the number off notes already present on the page
-: tbnoteid = the noteid from the database
The index is supposed too act like a counter of displayed messages.
If the counter exceeds 10 for example, it is supposed to delete the message on the criterium off last one is first one out (message with the oldest timestamp)from the page and the db(logic has too be added later)
The only action the form is permitted todo is delete the message from the database and remove itself(the container div) from the page.For estatic purposes it is first faded out.
The function can take more arguments like the message itself. When user enters the page the newnote function should be called from another function that pulls the messages from the db if there are any.
The link too generate a new note will be replaced by the action off another form like this example
$(document).ready(function(){
$('a[name=modal]').click(function(e) { //the selector is for testing purpose
//Cancel the link behavior
e.preventDefault();
var $aantal = $("div.pane").size()
newnote($number+1,1); // second argument is supposed too come from the database
});
function newnote(index,tbnoteid) {
$("div.wrapper:last").after('<div class="wrapper"></div>');
$('.wrapper:last').load('tbnote.html .pane', function() {
$(".pane:last").prepend("testmessage"); //testpurpose
$('.pane:last #frmnoteid').val(tbnoteid);
$(this,".frm" ).attr('id' , index);
var $id = $(this).attr('id'); "); //testpurpose
$('.frm:last').submit(function(){
$.post("tbnotes.php",{
noteid: $("#frmnoteid").val(),
actie: "verwijder",
tijd: timestamp}, function(xml) {
addMessages(xml);
});
alert("Hello mijn id = " + $id );"); //testpurpose
$(this).parents(".pane").animate({ opacity: 'hide' }, "slow");
$(this).parents(".wrapper").remove();
return false;
});
});
}
Upvotes: 0
Reputation: 10795
If you're using dynamically added forms, you should use the live
function in jQuery:
$('.submit').live('click', function(e) {
instead of
$('.submit').click(function(e) {
This binds the click callback to buttons with the submit
class even if new ones are added dynamically.
P.S. Sorry for bugging you about this but the clarifications you are adding in new answers to your own question should be appended to the original question, not added as answers. They are technically not answers.
Upvotes: 1
Reputation:
I think I ran into some syntax problem
I have my complete code here
the button is of type image
$(document).ready(function(){
timestamp = 0;
$('.delete').click(function(e) {
// load the form with closest (jQuery v1.3+)
var form = $(this).closest('form'); // check form
if (!form.attr('id')="noteform") {
e.preventDefault();
}
// or if you make the buttons of type button and not submit
if (form.attr('id')="noteform") {
form.submit(function(){
$(this).parents(".pane").animate({ opacity: 'hide' }, "slow");
$.post("tbnotes.php",{
noteid: $("#frmnoteid").val(),
action: "delete",
time: timestamp
}, function(xml) {
addMessages(xml);
});
return false;
});
} // end off IF(form.attr('id')="noteform")
}); //end off $('.delete).click(function(e) {
//select all the a tag with name equal to modal
$('a[name=modal]').click(function(e) {
//Cancel the link behavior
e.preventDefault();
// make a new note
newnote();
});
}); //end off document ready
Upvotes: 0
Reputation: 40235
I've seen some issues with the submit
event. I would recommend attaching your events to the button click events for your forms. I would also have to recommend that you don't use the same ids in html if possible. That's generally bad practice.
For example:
with the following html:
<form id="questionForm" action="question/save/1234" method="post">>
<input type="text" id="question1" />
<input type="text" id="answer1" />
<input type="submit" id="saveQuestion1" class="submit" value="Save" />
</form>
<!-- more forms -->
<form id="questionForm" action="question/save/4321" method="post">
<input type="text" id="question2" />
<input type="text" id="answer2" />
<input type="submit" id="saveQuestion2" class="submit" value="Save" />
</form>
You could use this instead:
$(document).ready(function() {
$('.submit').click(function(e) {
// load the form with closest (jQuery v1.3+)
var form = $(this).closest('form');
// check form
if (!isValid(form))
{
e.preventDefault();
}
// or if you make the buttons of type button and not submit
if (isValid(form))
{
form.submit();
}
});
});
Upvotes: 0
Reputation:
the last option I was actually thinking about it because I already used that code somewhere else
If that is really working, then that would be great
too check if the form is valid I could use instead off
if (!isValid(form))
if form.id="tbnoteform" then
submit the form
I still trying to get the hang off this
Can you use the keyword this everytime after you used the selector statement too create an object instance?? so form is now an object instance off the form?
Richard
Upvotes: 0