Bind dynamically added form to dispatch event using jQuery

What's the best way to handle the submit event when you have multiple forms dynamically created with the same form id in jQuery?

For now, this line makes jQuery only process the first form.

$("form#noteform").submit(function(){
  // do stuff
});

      

Kind of confusing because I really need to catch a submission of a specific form in order to get the correct message values, so the form selector must be unique.

How can you make it listen for all messages and later determine if it is the correct form id that triggered the submission?

0


a source to share


8 answers


There is no better way to do this with an ID, because having multiple elements with the same ID is invalid HTML.

I would suggest that your forms have a unique identifier instead, but together with the class name. If you then need to get the first one, you can use the ID directly or the class and jquery: first selector.

$('form.className:first').submit(function(){
  stuff();
});

      



-edit- Attempt to solve a form identification problem. Again this solution relies on unique form IDs

$('form.className').submit(function(){
  switch( $(this).attr('id') ){
    case 'form1id':
      submitForm1();
      break;
    case 'form2id':
      submitForm2();
      break;
    default:
      stuff()
      break;
  }      
});

      

+4


a source


If you are using dynamically added forms you must use the function live

in jQuery:

  $('.submit').live('click', function(e) {

      

instead



  $('.submit').click(function(e) {

      

This binds the click callback to the class buttons submit

, even if new ones are dynamically added.

PS Sorry for trying about this, but the clarifications you add to new answers to your question must be added to the original question, not added as answers. They don't technically answer.

+1


a source


I've seen some problems with the event submit

. I would recommend attaching your events to the button click events for your forms. I would also have to recommend that you do not use the same ids in html if possible. This is generally bad practice.

For instance:

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 can 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();
    }
  });
});

      

0


a source


the last option I really thought about this because I already used this code somewhere else

If it really works then that would be great

check if the form is valid too, I could use instead

if (!isValid(form))  

if form.id="tbnoteform" then
submit the form  

      

I'm still trying to untie this

Can you use the this keyword everytime after you've used the selector operator, instantiate the object too? so the form is now an instance of an object outside the form?

Richard

0


a source


I think I ran into a syntax problem

I have complete code here

the button is of the image type

$(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(); 

    }); 

      

}); // completion of document preparation

0


a source


I completely 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 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>

      

0


a source


I revised my example code for creating a new note

This adds to the submit event also the added form in the shutdown callback function of the load event.

This is a step forward because for some reason the other examples diddn't do the job.

I don't know of any disadvantages of doing it this way, but !! I am open to any comments on this issue If you want see example

Purpose & Comments: The newnote function takes two arguments

-: index = number of notes already present on the page

-: tbnoteid = note from database

It is assumed that the index also acts as a counter of displayed messages.

If the counter is greater than 10, for example, it should remove the post in the criteria, the last of which is the first (post with the oldest timestamp) from the page and db (logic will be added later too)

The only action allowed for the form is to remove the post from the database and remove itself (the div container) from the page. For aesthetic purposes, it disappears first.

The function can take more arguments, such as the message itself. When the user enters the page, the newnote function should be called from another function that fetches messages from the db, if any.

The link also generates a new note that will be replaced by an action from a different form, for example 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;

            });
        });

}   

      

0


a source


What would be the best way to handle an event submit when you have multiple forms dynamically created using the same form id in jQuery?

If id is 'noteform', to select the entire form with that id:

jQuery('form[id="noteform"]')

      

Attention . It might not be a good idea to have multiple HTML elements (including a form) in order to have a non-unique ID.

How can you make him listen to all the presents?

You can bind an event to your event:

jQuery('form[id="noteform"]').submit(function(e){});

      

and then determine if it is the correct form id that started submit?

Although the selector is guaranteed to have the correct ID in my opinion, you can check the ID of the form in the submit event using this object like

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 the POC code snippet that I use to test them (solve), 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.

0


a source







All Articles