添加按钮,将创建新的下拉列表并从新的dpl中删除所选的值

时间:2017-09-27 15:33:34

标签: javascript jquery list dropdown

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

我试过这个[例子] [1]但它不起作用!任何提示?

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

HTML CODE

    <div id="services-D" class="oneField" >                 
                    <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($dbc,"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>

                </div>
<button type="button" id="btn_add_service"   style="">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)

不确定这是否真的很符合您的要求,但我已根据您的说明尝试制作。希望this link可以帮助你。

HTML:

<select onchange="NewSelection(this);">
  <option>Select an option</option>
  <option>Option 1</option>
  <option>Option 2</option>
  <option>Option 3</option>
  <option>Option 4</option>
  <option>Option 5</option>
</select>

JavaScript / JQuery:

function NewSelection(selector){
    selected = $(selector).prop('selectedIndex');
    if (selected != 0 && $(selector).find('option').length != 2){
    newselector = $('<select onchange="NewSelection(this);"></select>').insertAfter(selector);
    $(selector).find('option').each(function(index,item) {
      if (index != selected){
        $(newselector).append(item);
      }
    });
  }
}