绑定动态添加的表单以使用jQuery提交事件

时间:2022-06-09 08:00:28

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?

当您在jQuery中使用相同的表单ID动态创建多个表单时,处理提交事件的最佳方法是什么?

So far this line makes that jQuery only handles the first form.

到目前为止,这一行使得jQuery只处理第一种形式。

$("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?

如何让它听取所有提交,然后确定它是否是启动提交的正确表单ID?

8 个解决方案

#1


There is no best way to do this using ID's, because having multiple elements with the same ID is invalid HTML.

没有使用ID的最佳方法,因为具有相同ID的多个元素是无效的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.

我建议你的表格有唯一的ID,但共享一个类名。如果你需要获得第一个,你可以直接使用ID或类和jquery:first选择器。

$('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

-edit-试图真正解决识别哪个表单已提交的问题。此解决方案再次依赖于唯一表单ID

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

#2


If you're using dynamically added forms, you should use the live function in jQuery:

如果您使用的是动态添加的表单,则应该使用jQuery中的live函数:

  $('.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.

附:很抱歉打扰你这个问题,但你在自己的问题的新答案中添加的说明应该附在原始问题上,而不是作为答案添加。从技术上讲,它们不是答案。

#3


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?

在使用了selector语句之后每次都可以使用关键字this也创建一个对象实例吗?所以form现在是一个表格外的对象实例?

Richard

#4


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.

我已经看到了提交事件的一些问题。我建议您将事件附加到表单的按钮单击事件。如果可能的话,我还要建议您不要在html中使用相同的ID。这通常是不好的做法。

For example:

with the following html:

使用以下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();
    }
  });
});

#5


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) {

}); //结束$('。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

}); //结束文档就绪

#6


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.

这个也将提交事件附加到load事件中的新回放函数中。

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

目的和评论:newnote函数有两个参数

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

- :index =页面上已存在的注释数量

-: tbnoteid = the noteid from the database

- :tbnoteid =数据库中的noteid

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)

例如,如果计数器超过10,则应该删除标准上的消息,最后一个是从页面开始的第一个输出(具有最早时间戳的消息)和db(逻辑也在以后添加)

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.

表单允许的唯一操作是删除数据库中的消息并从页面中删除自身(容器div)。出于静态目的,它首先被淡出。

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.

该函数可以采用更多参数,如消息本身。当用户进入页面时,应该从另一个函数调用newnote函数,该函数从db中提取消息(如果有的话)。

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;

            });
        });

}   

#7


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?

当您在jQuery中使用相同的表单ID动态创建多个表单时,处理提交事件的最佳方法是什么?

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

如果id为'noteform',则选择具有该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.

警告:让多个HTML元素(包括表单)具有非唯一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?

然后确定,如果它是启动提交的正确表单ID?

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:

虽然通过使用选择器,我保证(在我看来)具有正确id的表单,您可以使用此对象检查提交事件中表单的ID,例如:

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:

如果您对我用来测试它们的POC代码片段感兴趣(解决方案),这里是:

<!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.

#8


I've complete reworked my answer... It's cleaner, simpler, and it works for dynamically added forms too! ;-P

我完全重写了我的答案......它更干净,更简单,也适用于动态添加的表格! ;-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>

#1


There is no best way to do this using ID's, because having multiple elements with the same ID is invalid HTML.

没有使用ID的最佳方法,因为具有相同ID的多个元素是无效的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.

我建议你的表格有唯一的ID,但共享一个类名。如果你需要获得第一个,你可以直接使用ID或类和jquery:first选择器。

$('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

-edit-试图真正解决识别哪个表单已提交的问题。此解决方案再次依赖于唯一表单ID

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

#2


If you're using dynamically added forms, you should use the live function in jQuery:

如果您使用的是动态添加的表单,则应该使用jQuery中的live函数:

  $('.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.

附:很抱歉打扰你这个问题,但你在自己的问题的新答案中添加的说明应该附在原始问题上,而不是作为答案添加。从技术上讲,它们不是答案。

#3


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?

在使用了selector语句之后每次都可以使用关键字this也创建一个对象实例吗?所以form现在是一个表格外的对象实例?

Richard

#4


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.

我已经看到了提交事件的一些问题。我建议您将事件附加到表单的按钮单击事件。如果可能的话,我还要建议您不要在html中使用相同的ID。这通常是不好的做法。

For example:

with the following html:

使用以下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();
    }
  });
});

#5


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) {

}); //结束$('。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

}); //结束文档就绪

#6


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.

这个也将提交事件附加到load事件中的新回放函数中。

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

目的和评论:newnote函数有两个参数

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

- :index =页面上已存在的注释数量

-: tbnoteid = the noteid from the database

- :tbnoteid =数据库中的noteid

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)

例如,如果计数器超过10,则应该删除标准上的消息,最后一个是从页面开始的第一个输出(具有最早时间戳的消息)和db(逻辑也在以后添加)

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.

表单允许的唯一操作是删除数据库中的消息并从页面中删除自身(容器div)。出于静态目的,它首先被淡出。

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.

该函数可以采用更多参数,如消息本身。当用户进入页面时,应该从另一个函数调用newnote函数,该函数从db中提取消息(如果有的话)。

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;

            });
        });

}   

#7


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?

当您在jQuery中使用相同的表单ID动态创建多个表单时,处理提交事件的最佳方法是什么?

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

如果id为'noteform',则选择具有该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.

警告:让多个HTML元素(包括表单)具有非唯一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?

然后确定,如果它是启动提交的正确表单ID?

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:

虽然通过使用选择器,我保证(在我看来)具有正确id的表单,您可以使用此对象检查提交事件中表单的ID,例如:

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:

如果您对我用来测试它们的POC代码片段感兴趣(解决方案),这里是:

<!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.

#8


I've complete reworked my answer... It's cleaner, simpler, and it works for dynamically added forms too! ;-P

我完全重写了我的答案......它更干净,更简单,也适用于动态添加的表格! ;-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>