javascript - <select> 输入上的 Jquery .on(change) 事件仅更改第一行。

标签 javascript php jquery html mysql

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

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

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

我一直在绞尽脑汁,试图弄清楚我是否需​​要(如果需要的话如何)动态更改事件绑定(bind)的 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.

最佳答案

工作示例: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()绑定(bind)到它们中的每一个。

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

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

关于javascript - <select> 输入上的 Jquery .on(change) 事件仅更改第一行。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34746133/

相关文章:

javascript - .then() 回调中的 `return` 是从内部作用域还是外部作用域返回?

javascript - 如何从多选选项中获取数据属性?

php多线程变量范围共享问题

php - Symfony3 中的 access_control 不起作用

java - 我在这个用于 netbeans 的 Java 正则表达式中缺少什么替换

javascript - 如何动态生成JSon对象?

javascript - 根据里面的单选按钮更改 div 的类?

javascript - 删除下钻标签的下划线

javascript - 如何从确认对话框插件返回 bool 值?

javascript - 删除 onclick 函数