附加jQuery的后动态输入

Post Dynamic Inputs that are Appended with jQuery

本文关键字:动态 输入 jQuery 附加      更新时间:2023-09-29

我发现了多个相同的问题,其中包括:

  • 动态插入的表单输入不会发布

  • jQuery没有在.append()之后发布表单的所有输入

大多数问题都是由在表/div中打开表单或HTML的其他问题引起的。我不认为我有这两个问题;我怀疑我的javascript需要调整。

我使用jQuery是这样的:

<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
</head>
  1. 当点击添加链接时,一个新的表格行被添加到tbody.newRow

  2. 单击.remove时,系统会要求您进行确认。确认后,该行将被删除。

  3. input.Value失去焦点时,表单通过ajax提交。

jQuery:

$(document).ready(function() {
  $(".add").on('click', function() {
    $("tbody.newRow").append(
      '<tr><td><input type="text" name="NewJobLeviesId[]" class="JobLeviesId" /><input type="text" name="NewValue[]" class="Value" /><input type="text" name="MasterId[]" class="Values" /><input type="text" name="LUPChoiceId[]" class="Values" /><input type="text" name="SortOrder[]" class="Values" /></td><td class="removeSelection"><a href="#" class="remove">Remove</a></td></tr>'
    );
  });
  $("tbody").on('click', '.remove', function() {
    $(this).parent().append($(
      '<div class="confirmation"><a href="#" class="removeConfirm">Yes</a><a href="#" class="removeCancel">No</a></div>'
    ))
    $(this).remove();
  });
  $("tbody").on('click', '.removeConfirm', function() {
    $(this).parent().parent().parent().remove();
  });
  $("tbody").on('click', '.removeCancel', function() {
    $(this).parent().parent().append(
      '<a href="#" class="remove">Remove</a>');
    $(this).parent().remove();
  });
  var formTwo = $('.ajaxTwo'); // contact form
  // form submit event
  $(".Value").blur(function() {
    $.ajax({
      type: 'POST', // form submit method get/post
      dataType: 'html', // request type html/json/xml
      data: formTwo.serialize(), // serialize form data 
      success: function(data) {
        url: 'functions.php'; // form action url
      },
      error: function(e) {
        console.log(e)
      }
    });
  });
});

ajax可以很好地处理未动态添加的现有行。添加行位于表页脚中,看起来很漂亮。表单以数组形式发布。

<form class="ajaxTwo" method="post">
    <table>
    <tbody class="newRow">
        <tr>
          <td>
              <input type="text" name="NewJobLeviesId[]" class="JobLeviesId" />
              <input type="text" name="NewValue[]" class="Value" />
              <input type="text" name="MasterId[]" class="Values" />
              <input type="text" name="LUPChoiceId[]" class="Values" />
              <input type="text" name="SortOrder[]" class="Values" />
          </td>
          <td class="removeSelection">
              <a href="#" class="remove">Remove</a>
          </td>
        </tr>
    </tbody>
   <tfoot>
        <tr>
           <td>
               <a href="#" class="add">Add Row</a>
           </td>
        </tr>
    </tfoot>
    </table>
</form>

最后是php。每一行都插入到我的数据库表中,并带有一个PDO准备的语句。

if(isset($_SERVER['HTTP_X_REQUESTED_WITH'])){
    if(isset($_POST['NewJobLeviesId'])) {
        for($i=0; $i<count($_POST['NewJobLeviesId']); $i++) {
          $NewJobLeviesId = $_POST['NewJobLeviesId'][$i];
          $NewValue = $_POST['NewValue'][$i];
          $MasterId = $_POST['MasterId'][$i];
          $LUPChoiceId = $_POST['LUPChoiceId'][$i];
          $SortOrder = $_POST['SortOrder'][$i];
          $sql = "INSERT INTO joblevies (JobLeviesId,Value,MasterId,LUPChoiceId,SortOrder) VALUES (:JobLeviesId,:Value,:MasterId,:LUPChoiceId,:SortOrder)";
        $q = $db->prepare($sql);
        $q->execute(array(':JobLeviesId'=>($NewJobLeviesId),':Value'=>($NewValue),':MasterId'=>($MasterId),':LUPChoiceId'=>($LUPChoiceId),':SortOrder'=>($SortOrder)));
        }
    }
}

同样,这非常有效。只有动态添加的输入才有问题。我错过了什么?

动态创建的dom元素没有您在$(document).ready(...上附加的任何事件,因为在附加事件时它们还不存在。所以$('.Value').blur(...的东西只附在第一个形式上,而不是任何未来的形式。因此,每次创建新行时都要附加事件,所以可能是这样的:

首先,将绑定操作委托给自己的函数

function attachSubmitEvent() {
    // form submit event
    //remove old events first
    $(".Value").off();
    $(".Value").blur(function () {
        var formTwo = $('.ajaxTwo'); // contact form
        $.ajax({
            type: 'POST', // form submit method get/post
            dataType: 'html', // request type html/json/xml
            data: formTwo.serialize(), // serialize form data 
            success: function (data) {
                url: 'functions.php'; // form action url
            },
            error: function (e) {
                console.log(e)
            }
        });
    });
}

然后在您的文档中。准备,调用该函数

attachSubmitEvent();

然后,为了确保它们也附加到新元素上,在创建新元素时再次调用它

$(".add").on('click', function () {
$("tbody.newRow").append('<tr><td><input type="text" name="NewJobLeviesId[]" class="JobLeviesId" /><input type="text" name="NewValue[]" class="Value" /><input type="text" name="MasterId[]" class="Values" /><input type="text" name="LUPChoiceId[]" class="Values" /><input type="text" name="SortOrder[]" class="Values" /></td><td class="removeSelection"><a href="#" class="remove">Remove</a></td></tr>');
attachSubmitEvent(); //now everyone has the event attached.
});

对于表单提交事件,请尝试:

$("tbody").on('focusout', '.Value', function() {
    ...
});

您也可以在此事件处理程序中使用blur,但为了清楚起见,文档建议使用focusout(请参阅jQuery on()方法文档的"附加说明"部分:http://api.jquery.com/on/)