jquery - 添加创建新选择列表的按钮,而不包含先前选择的值

时间:2017-09-28 09:42:59

标签: javascript jquery html

我需要创建一个添加按钮,每次用户按下它时,都会创建一个新的下拉列表,并且所选的值不会出现在新的dpl中。第一个下拉列表也是从数据库中获取数据(已完成)。

下面的代码有一个按钮,每次按下时都应创建一个新的dpl,其中包含所有先前的值减去用户选择的值,但它只创建一个dpl,就是这样。

我尝试过这样做example但它不起作用!任何提示?

此外,这是为了练习,所以不需要验证等等。

HTML CODE

    <label id="services-L" for="services" class="label preField reqMark" style="width: 100px; min-width:0">Services</label><br>
    <select id="c_service" name="c_service" class="required  dynamic-select" style="width:170px" >
    <option value="">Select Service...</option>
    <?php
        $res=mysqli_query($conn,"Select t1 t2 Where t4s = 'Y'");
        while ($row = mysqli_fetch_array($res)) { ?>
        <option value = <?php echo $row['invoice_code']?> > <?php echo $row['t1'] . ": " . $row['t2'];}?> </option>
    ?>
    </select>  
<button type="button" id="btn_add_service>Add Service</button>

jQuery

<script>
$('#btn_add_service').on('click', function() {  
    selected = $('#c_service').prop('selectedIndex');
    if (selected != 0 && $('#c_service').find('option').length != 2){
    newselector = $('<select id="c_service"></select>').insertAfter('#c_service');
    $('#c_service').find('option').each(function(index,item) {
      if (index != selected){
        $(newselector).append(item);
      }
    });
  }
});
</script>

1 个答案:

答案 0 :(得分:1)

你正在寻找这样的东西吗? 有主要选择并提供一些副本?

&#13;
&#13;
function ReplicaCtrl($) {
  const master = $('#MasterSelect');
  const btn = $('#btn_add_service');
  
  function serialize(select) {
    
    return Array
      .prototype
      .reduce
      .call(select.children(), 
      (res, item) => {
        return res.concat({
          value: item.value,
          label: item.textContent,
          selected: item.selected
        });
      }, [])
    ;
  }
  
  btn.click((event) => {
    
    return Promise
      .resolve(serialize(master))
      .then(options => {
        return options.filter(o => !o.selected);
      })
      .then(options => options.map(o => (
        `<option value="${o.value}">${o.label}</option>`
      )))
      .then(tpl => `<div><select>${tpl}</select></div>`)
      .then(select => $(select).insertAfter(master.parent()))
    ;
  });
}


jQuery(document).ready(ReplicaCtrl);
&#13;
div {
  margin: 5px;
  padding: 5px;
  background: cyan;
}
select { width: 100%; }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="btn_add_service">Add Service</button>
<hr />

<div>
  <select id="MasterSelect">
    <option value="foo">Foo</option>
    <option value="foo1">Foo1</option>
    <option value="foo2">Foo2</option>
    <option value="foo3">Foo3</option>
    <option value="foo4">Foo4</option>
  </select>
</div>
&#13;
&#13;
&#13;