添加具有unqiue名称的新选择以更改先前的选择

时间:2018-05-25 22:30:31

标签: javascript jquery html html-select onchange

我的工作需要在页面上有数百个select个元素。我希望动态显示每个select,因为之前已更改。我有一个工作版本,我将所有select元素放在标记中,然后使用一个简单的函数隐藏它们并仅显示第一个。然后在更改每个select时添加下一个。

这很好用,但显然不理想。我不想在标记中放置500个select项并且无缘无故地隐藏它们,我的JS函数将是1500行。再加上这会让我觉得很傻。

如何使用JS自动完成此过程?

我不需要每个select都有唯一的id,但我确实需要每个select都有一个唯一且递增的name。这可能吗?我有一份工作fiddle

HTML:

<select name="select-one" class="hidden" id="one">
   <option value="">not this one</option>
   <option value="">pick this one</option>
</select>

<select name="select-two" class="hidden" id="two">
   <option value="">not this one</option>
   <option value="">pick this one</option>
</select>

<select name="select-three" class="hidden" id="three">
   <option value="">not this one</option>
   <option value="">pick this one</option>
</select>

<select name="select-four" class="hidden" id="four">
   <option value="">not this one</option>
   <option value="">pick this one</option>
</select>

JS:

$(document).ready(function() {

  $('.hidden').hide();
  $('#one').show();

  $('#one').change(function(){
     $('#two').show();
  });
  $('#two').change(function(){
     $('#three').show();
  });
  $('#three').change(function(){
     $('#four').show();
  });
  // and so forth...

});

2 个答案:

答案 0 :(得分:2)

HTML

<select class="hidden" id="one" name='name_0'>
   <option value="">not this one</option>
   <option value="">pick this one</option>
</select>

<强>的jQuery

$('select').on('change', function() {
$('body').append($(this).clone(true))
})

结果

enter image description here

注意我们正在使用clone()方法的重载。这意味着事件处理程序和数据将与元素一起复制。因此,您附加到原始选择的任何事件处理程序都会被克隆。

如果您想增加名称,只需使用计数器并在克隆后添加属性

cnt=0;
$('select').on('change', function() {
cnt++
$('body').append($(this).clone(true).attr('name', 'name_' + cnt))
})

enter image description here

答案 1 :(得分:0)

我的解决方案:

CSS

.hidden {
  display: none;
}

JS

const createSelect = index => `
<select name="select-${index}" class="hidden select" data-index=${index}>
   <option value="">not this one</option>
   <option value="">pick this one</option>
</select>
`;

$(document).ready(function() {
  // Generate 100 selects
  for (let i = 0; i < 100; i++) {
    $("body").append(createSelect(i));
  }

  // Show first select
  $(`.select[data-index='0']`).show();

  $('.select').on('change', function() {
    // Store index of a select currently changed
    const index = parseInt($(this).attr('data-index'), 10);

    // Show next select
    $(`.select[data-index='${index + 1}']`).show();
  });
});
相关问题