【问题标题】:Jquery .on(change) event on <select> input only changes first row.<select> 输入上的 Jquery .on(change) 事件仅更改第一行。
【发布时间】:2016-01-13 08:51:16
【问题描述】:

我有一个表格,人们可以在其中添加行。

表中有一个选择输入,当更改时,会通过 ajax 更改第二个选择字段中的值。

我遇到的问题是,如果有人向表中添加了额外的行,.on(change) 事件会更改第一行中的第二个字段,而不是后续行。

我一直在绞尽脑汁,试图弄清楚我是否需​​要(如果需要,如何)动态更改事件绑定到的 div id 以及它影响的 div。这是解决方案吗?如果是这样,有人可以证明我将如何实现这一目标吗?

HTML 表单是

<form action="assets.php" method="post">
<button type="button" id="add">Add Row</button>
<button type="button" id="delete">Remove Row</button>
<table id="myassettable">
<tbody>
    <tr>
        <th>Asset Type</th>
    <th>Manufacturer</th>
    <th>Serial #</th>
    <th>MAC Address</th>
    <th>Description</th>
    <th>Site</th>
    <th>Location</th>
</tr>
<tr class="removable">
    <!--<td><input type="text" placeholder="First Name" name="contact[0][contact_first]"></td>
    <td><input type="text" placeholder="Surname" name="contact[0][contact_surname]"></td>-->
    <td><select name="asset[0][type]">
    <option><?php echo $typeoption ?></option>
    </select></td>
    <td><select class="manuf_name" name="asset[0][manuf]">
    <option><?php echo $manufoption ?></option>
    </select></td>
    <td><input type="text" placeholder="Serial #" name="asset[0][serial_num]"></td>
    <td><input type="text" placeholder="Mac Address" name="asset[0][mac_address]"></td>
    <td><input type="text" placeholder="Name or Description" name="asset[0][description]"></td>
    <td><select id="site" name="asset[0][site]">
    <option><?php echo $siteoption ?></option>
    </select></td>
    <td><input type="text" placeholder="e.g Level 3 Utility Room" name="asset[0][location]"></td>
    <td><select id="new_select" name="asset[0][contact]"></select></td>
    <!--<td><input type="email" placeholder="Email" name="contact[0][email]"></td>
    <td><input type="phone" placeholder="Phone No." name="contact[0][phone]"></td>
    <td><input type="text" placeholder="Extension" name="contact[0][extension]"></td>
    <td><input type="phone" placeholder="Mobile" name="contact[0][mobile]"></td>-->
</tr>
</tbody>
</table>
<input type="submit" value="Submit">
<input type="hidden" name="submitted" value="TRUE" />
</form>

我的脚本是

<script type="text/javascript">
$(document).ready(function() {
    $("#add").click(function() {
        var newgroup = $('#myassettable tbody>tr:last');
     newgroup
        .clone(true) 
        .find("input").val("").end()
     .insertAfter('#myassettable tbody>tr:last')
     .find(':input')
        .each(function(){
            this.name = this.name.replace(/\[(\d+)\]/,
            function(str,p1) {
            return '[' + (parseInt(p1,10)+1)+ ']'
            })

     })

            return false;         

      });


    });  

    $(document).ready(function() {
    $("#delete").click(function() {
        var $last = $('#myassettable tbody').find('tr:last')
        if ($last.is(':nth-child(2)')) {
            alert('This is the only one')
        } else {
     $last.remove()        
    }
 });
 });

$(document).ready(function() {
$("#myassettable").on("change","#site",function(event) {
    $.ajax ({
        type    :   'post',
        url : 'assetprocess.php',
        data: {
        get_option  :   $(this).val()           
        },
        success: function (response) {
    document.getElementById("new_select").innerHTML=response;
}                   
            })  
        }); 
    });

</script>

而assetprocess.php页面是

<?php
if(isset($_POST['get_option'])) {

//Get the Site Contacts

$site = $_POST['get_option'];
$contact = "SELECT site_id, contact_id, AES_DECRYPT(contact_first,'" .$kresult."'),AES_DECRYPT(contact_surname,'" .$kresult."') FROM contact WHERE site_id = '$site' ORDER BY contact_surname ASC";
$contactq = mysqli_query($dbc,$contact) or trigger_error("Query: $contact\n<br />MySQL Error: " .mysqli_errno($dbc));

if ($contactq){
//$contactoption = '';
echo '<option>Select a Contact (Optional)</option>';
while ($contactrow = mysqli_fetch_assoc($contactq)) {
    $contactid = $contactrow['contact_id'];
    $contactfirst = $contactrow["AES_DECRYPT(contact_first,'" .$kresult."')"];
    $contactsurname = $contactrow["AES_DECRYPT(contact_surname,'" .$kresult."')"];
$contactoption .= '<option value="'.$contactid.'">'.$contactsurname.', '.$contactfirst.'</option>';
echo $contactoption;
}
}

exit;

}
?>

代码丑得像罪恶,但这只是现阶段的自利项目。

任何帮助将不胜感激。

干杯,

J。

【问题讨论】:

  • 阅读文档中以Delegated events have the advantage that they can process events from descendant elements.... 开头的段落 (api.jquery.com/on)
  • html 中的 ID 必须是唯一的。当您克隆该行时,您添加了具有相同 ID 的重复元素,其中 &lt;select id="site" name="asset[0][site]"&gt; 现在您已经破坏了 dom,发生了不可预知的事情。而是使用可以复制的类
  • @OfirBaruch OP 使用事件委托,只是有重复的ID
  • 创建的小提琴:jsfiddle.net/Twisty/1c98Ladh

标签: javascript php jquery html mysql


【解决方案1】:

工作示例:https://jsfiddle.net/Twisty/1c98Ladh/3/

一些小的 HTML 更改:

<form action="assets.php" method="post">
  <button type="button" id="add">Add Row</button>
  <button type="button" id="delete">Remove Row</button>
  <table id="myassettable">
    <tbody>
      <tr>
        <th>Asset Type</th>
        <th>Manufacturer</th>
        <th>Serial #</th>
        <th>MAC Address</th>
        <th>Description</th>
        <th>Site</th>
        <th>Location</th>
      </tr>
      <tr class="removable">
        <td>
          <select name="asset[0][type]">
            <option>---</option>
            <option>Type Option</option>
          </select>
        </td>
        <td>
          <select class="manuf_name" name="asset[0][manuf]">
            <option>---</option>
            <option>
              Manuf Option
            </option>
          </select>
        </td>
        <td>
          <input type="text" placeholder="Serial #" name="asset[0][serial_num]">
        </td>
        <td>
          <input type="text" placeholder="Mac Address" name="asset[0][mac_address]">
        </td>
        <td>
          <input type="text" placeholder="Name or Description" name="asset[0][description]">
        </td>
        <td>
          <select id="site-0" class="chooseSite" name="asset[0][site]">
            <option>---</option>
            <option>
              Site Option
            </option>
          </select>
        </td>
        <td>
          <input type="text" placeholder="e.g Level 3 Utility Room" name="asset[0][location]">
        </td>
        <td>
          <select id="new-site-0" name="asset[0][contact]">
          </select>
        </td>
      </tr>
    </tbody>
  </table>
  <input type="submit" value="Submit">
  <input type="hidden" name="submitted" value="TRUE" />
</form>

这准备id 在我们添加新元素时递增。使用class,我们可以将.change()绑定到每个人。

$(document).ready(function() {
  $("#add").click(function() {
    var newgroup = $('#myassettable tbody>tr:last');
    newgroup
      .clone(true)
      .find("input").val("").end()
      .insertAfter('#myassettable tbody>tr:last')
      .find(':input')
      .each(function() {
        this.name = this.name.replace(/\[(\d+)\]/,
          function(str, p1) {
            return '[' + (parseInt(p1, 10) + 1) + ']';
          });
      });
    var lastId = parseInt(newgroup.find(".chooseSite").attr("id").substring(5), 10);
    newId = lastId + 1;
    $("#myassettable tbody>tr:last .chooseSite").attr("id", "site-" + newId);
    $("#myassettable tbody>tr:last select[id='new-site-" + lastId + "']").attr("id", "new-site-" + newId);
    return false;
  });

  $("#delete").click(function() {
    var $last = $('#myassettable tbody').find('tr:last');
    if ($last.is(':nth-child(2)')) {
      alert('This is the only one');
    } else {
      $last.remove();
    }
  });

  $(".chooseSite").change(function(event) {
    console.log($(this).attr("id") + " changed to " + $(this).val());
    var target = "new-" + $(this).attr('id');
    /*$.ajax({
      type: 'post',
      url: 'assetprocess.php',
      data: {
        get_option: $(this).val()
      },
      success: function(response) {
        $("#" + target).html(response);
      }
      });*/
    var response = "<option>New</option>";
    $("#" + target).html(response);
  });
});

可以通过在全局空间中为行数设置一个计数器来节省一些时间,例如 var trCount = 1; 并使用它来设置数组索引和 ID。克隆既快速又简单,但这也意味着我们必须返回并附加各种属性。还可以创建一个函数来为您绘制 HTML。点赞:https://jsfiddle.net/Twisty/1c98Ladh/10/

function cloneRow(n) {
  if (n - 1 < 0) return false;
  var html = "";
  html += "<tr class='removable' data-row=" + n + ">";
  html += "<td><select name='asset[" + n + "][type]' id='type-" + n + "'>";
  html += $("#type-" + (n - 1)).html();
  html += "<select></td>";
  html += "<td><select name='asset[" + n + "][manuf]' id='manuf-" + n + "'>";
  html += $("#manuf-" + (n - 1)).html();
  html += "<select></td>";
  html += "<td><input type='text' placeholder='Serial #' name='asset[" + n + "][serial_num]' id='serial-" + n + "' /></td>";
  html += "<td><input type='text' placeholder='MAC Address' name='asset[" + n + "][mac_address]' id='mac-" + n + "' /></td>";
  html += "<td><input type='text' placeholder='Name or Desc.' name='asset[" + n + "][description]' id='desc-" + n + "' /></td>";
  html += "<td><select name='asset[" + n + "][site]' class='chooseSite' id='site-" + n + "'>";
  html += $("#site-" + (n - 1)).html();
  html += "<select></td>";
  html += "<td><input type='text' placeholder='E.G. Level 3 Utility Room' name='asset[" + n + "][location]' id='loc-" + n + "' /></td>";
  html += "<td><select name='asset[" + n + "][contact]' id='contact-" + n + "'><select></td>";
  html += "</tr>";
  return html;
}

前期工作较多,但对每个部分提供了更多控制。并且以后使用起来更容易。

【讨论】:

  • 哇。惊人的。太感谢了。这解决了问题。我的赞成票还没有公开出现的分数,但我已经对答案投了赞成票。再次感谢您。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多