javascript - 如何使用循环设置一组文本框的 id

标签 javascript jquery

您好,我正在尝试在按下删除按钮时保留一组文本框的 ID 属性。

我想做的是,当按下删除按钮时,读取现有的文本框并保留 id,因为当我删除项目时,现有的 ID 一旦保留旧的 ID 值,我想保留它以匹配错误号值(value)。

工作 jsFiddle

//Add and remove function for the error text boxes
$(document).ready(function() {
  $(document).on('click', '.addRow', function() {
    var div = $("<div />"),
      btnId = $("#stValue").val(); //Breaks the number from the ID using .match
    // btnId = $(this).data("bid").match(/\d+/);//Breaks the number from the ID using .match

    div.html(copy()); //Creates a new div container
    $('.error-Column').append(div); //Insert all the HTML into the new div

    $('#addRow_' + btnId).prop("disabled", true); //Disables the add button once clicked.
    resetErrorNo(); //Calls the reset function
  });

  //Remove the text filed from the list and resets the error number
  $(document).on('click', '.delRow', function() {
    if (confirm('Your sure you want to remove this?')) {
      var btnId = $("#stValue").val(), //Read the value of stValue
        btnId2 = btnId - 1; //Deduct 1 from the value to get the last ID

      for (var i = 0; i < btnId; i++) {
        $('.addRow').attr('id', 'addRow_' + i);
      }
      //Enables the 1st add button if the value equals 1
      if (btnId2 === 1) {
        $('#addRow_' + btnId2).prop('disabled', false);
      } else {
        $('#addRow_' + btnId).prop('disabled', false);
      }

      $(this).parent().remove(); //Remove the text row from the list.
      resetErrorNo(); //Calls the reset function
    }
  });
});

//Reset the entire error count number index
function resetErrorNo() {
  $(".errorCount").each(function(index, _this) {
    $(this).val(index + 1);
    $("#stValue").val(index + 1);
  });
}

//HTML function which will be called by the button click event for the add button
function copy() {
  var stNum = document.getElementById("stValue"),
    genNum = (document.getElementById("stValue").value - 1) + 2;

  // stNum.value = genNum;

  // language=HTML
  return '<input class="errorCount" size="1" value="' + genNum + '" style="margin-left: 2%" readonly/>\n' +
    '<select class="errorName" style="margin-left: 6%">\n' +
    '<option selected disabled>----- Select Error -----</option>\n' +
    '</select>\n' +
    '<input type="button" class="addRow" id="addRow_' + genNum + '" data-bid="addRow_' + genNum + '" value="Add" />\n' +
    '<input type="button" class="delRow" id="delRow_' + genNum + '" data-bid="delRow_' + genNum + '" value="Delete"/><br />'
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="jType-container">
  <div id="error-Add-Container">
    <div id="error-Column-Headings">
      Error Number<span style="margin-left: 8%">Error Name</span>
    </div>
    <div class="error-Column">
      <input class="errorCount" size="1" value="1" style="margin-left: 2%" />
      <input type="hidden" value="1" id="stValue" />
      <select class="errorName" style="margin-left: 6%">
                             <option selected disabled>----- Select Error -----</option>
                         </select>
      <input type="button" data-bid="addRow_1" id="addRow_1" class="addRow" value="Add" />
    </div>
  </div>
</div>

更新:我使用了@Rory McCrossan 给出的答案,并进行了一些调整以获得我想要的结果,最终得到了下面的代码,这正是我最初想要做的。

// Add and remove function for the error text boxes
$(document).ready(function() {
  $(document).on('click', '.addRow', function() {
    var $clone = $('.error-Column .error-container:first').clone().appendTo('.error-Column');
    $clone.find('select').val('');
    // $clone.find('input').val('');
    $('.addRow').prop('disabled', true).filter(':last').prop('disabled', false);
    resetErrorNo();
  }).on('click', '.delRow', function() {
    var $btn = $(this);
    if (confirm('Your sure you want to remove this?')) {
      $btn.closest('.error-container').remove();
      $('.addRow').prop('disabled', true).filter(':last').prop('disabled', false);
      resetErrorNo();
    }
  });
});

//Reset the entire error count number index
function resetErrorNo() {
  $(".errorCount").each(function(index, _this) {
    $(this).val(index + 1);
  });
}
/*----- All the styling for the error input area start -----*/

#error-Column-Headings span {
  margin-left: 8%;
}

.errorCount {
  margin-left: 2%;
}

.errorName {
  margin-left: 6%;
}

.error-Column .error-container:nth-child(1) .delRow {
  display: none;
}

.error-Column .error-container:nth-child(1) .delRow {
  display: none;
}


/*----- All the styling for the error input area end -----*/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="jType-container">
  <div id="error-Add-Container">
    <div id="error-Column-Headings">
      Error Number<span>Error Name</span>
    </div>
    <div class="error-Column">
      <div class="error-container">
        <input class="errorCount" size="1" value="1" style="margin-left: 2%" />
        <select class="errorName">
                                 <option selected disabled value="">----- Select Error -----</option>
                             </select>
        <input type="button" class="addRow" value="Add" />
        <input type="button" class="delRow" value="Delete" />
      </div>
    </div>
  </div>
希望这对以后的人有所帮助。

最佳答案

增量 id 属性是一种反模式,它会导致大量不必要的维护工作 - 正如您所发现的。

您可以使您的代码更干,更不用说通过简单地克隆每一行并使用 DOM 遍历来查找与按钮相关的元素并根据需要添加/删除它们来使代码更简单。试试这个:

//Add and remove function for the error text boxes
$(document).ready(function() {
  $(document).on('click', '.addRow', function() {
    var $clone = $('.error-Column .error-container:first').clone().appendTo('.error-Column');
    $clone.find('select').val('');
    $('.addRow').prop('disabled', true).filter(':last').prop('disabled', false);
  }).on('click', '.delRow', function() {
    var $btn = $(this);
    if (confirm('Your sure you want to remove this?')) {
      $btn.closest('.error-container').remove();
      $('.addRow').prop('disabled', true).filter(':last').prop('disabled', false);
    }
  });
});
#error-Column-Headings span {
  margin-left: 8%;
}
.errorCount { 
  margin-left: 2%;
}
.errorName {
  margin-left: 6%;
}
.error-Column .error-container:nth-child(1) .delRow {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="jType-container">
  <div id="error-Add-Container">
    <div id="error-Column-Headings">
      Error Number <span>Error Name</span>
    </div>
    <div class="error-Column">
      <div class="error-container">
        <select class="errorName">
          <option selected disabled value="">----- Select Error -----</option>
        </select>
        <input type="button" class="addRow" value="Add" />
        <input type="button" class="delRow" value="Delete" />
      </div>
    </div>
  </div>
</div>

关于javascript - 如何使用循环设置一组文本框的 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45836849/

相关文章:

jquery - 绑定(bind)dialogopen事件

javascript - jQuery 找不到具有指定 id 的元素

javascript - 悬停时停止通知超时

javascript - 验证 Javascript 中的文本区域

javascript - Jquery在div内后拉伸(stretch)?

javascript - window.location.hash 返回未定义,脚本将无法显示正确的页面

javascript - $(document).ready() 立即触发 window.open() 上下文

java - 异步调用问题

javascript - `if __name__ == ' __main__ '` 相当于 javascript es6 模块

jQuery:WAITING元素(视频标签 - 动态生成)加载