添加新行时,jQuery保留select选项的值

时间:2013-12-02 12:39:13

标签: jquery

我有一个表单,我有一个按钮来添加具有增量行ID号的行。使用新行我删除按钮以删除新添加的行。当输入的值和添加行被单击时,值将在新行中清除,之前的值将在旧行中。它正常工作。但是在表单中我有一个下拉值(选择选项),当我添加另一行时,下拉列表中选择的值是清除而不显示先前选择的值? 这是

的代码

的CSS:

.remove { display: none; }

JS:

jQuery(document).ready(function() {
          var template = jQuery('#template');
          id = 0;
          jQuery('#addrow').click(function(){
            var row = jQuery(template).clone();
            template.find("input:text").val("");
            row.attr('id', 'row_' + (++id));
            row.find('.remove').show();
            template.before(row);
          });

          jQuery(document).on('click','.remove',function() {
            jQuery(this).closest('tr').remove();
          });

        });

HTML:

<table>
  <tr>
    <th>Option</th>
    <th>From Price</th>
    <th>To Price</th>
    <th></th>
  </tr>
  <tr id="template">
    <td>
      <select name="option" id="option">
        <option value="" selected>--select--</option>
        <option value="one">One</option>
        <option value="two">Two</option>
        <option value="three">Three</option>
        <option value="four">Four</option>
      </select>
    </td>
    <td><input type="text" name="from-price" id="from-price" /></td>
    <td><input type="text" name="to-price" id="to-price" /></td>
    <td><input type="button" class="remove" value="remove" /></td>
  </tr>
</table>
<input type="button" id="addrow" value="+Add Row" />

有人可以告诉我如何在新行中保留旧行中的下拉值吗?

1 个答案:

答案 0 :(得分:1)

我认为这个JS会做你想要的。

jQuery('#addrow').click(function(){
    var row = jQuery(template).clone();
    var templateSelectedIndex = template.find("select")[0].selectedIndex;
    template.find("input:text").val("");
    row.attr('id', 'row_' + (++id));
    row.find('.remove').show();
    row.find("select")[0].selectedIndex = templateSelectedIndex;
    template.before(row);
});

演示:http://jsfiddle.net/e5ZBf/

请注意,我已避免使用ID选择您的选择框,因为您在具有相同ID的页面上复制它。这可能会导致意外结果。你应该用类名替换id="option"。您正在克隆的其他元素也是如此。

相关问题