2017-05-25 72 views
-1

我有一個下拉列表,我想要做的是當我從這個列表中選擇一個選項時,它顯示一個按鈕下的選項,用戶可以選擇多個選項,所以我想要顯示許多按鈕與一個密切的標誌,以便用戶可以刪除該選項,我該怎麼做,使用JavaScript?這裏是我的代碼:在按鈕中顯示下拉選項

$('select').on('change', function() { 
 
    var unselected = $('select').filter(function() { 
 
    return this; 
 
     $('.btn').show(); 
 

 
    }); 
 
});
.btn{ 
 
display:none;}
<div class="form-group"> 
 
    <label>Pick your item</label> 
 
    <select class="form-control"> 
 
    <option>Item 1</option> 
 
    <option>Item 2</option> 
 
    <option>Item 3</option> 
 
    <option>Item 4</option> 
 
    </select> 
 
</div> 
 
    
 
<button type="button" class="btn btn-default">Chosen value should be here</button>

+0

爲什麼不直接使用多選插件在那裏?比創建自己的更好。看看[選擇](https://harvesthq.github.io/chosen/),看看是否會做你想要的 –

+0

按鈕或複選框? – Tushar

回答

2

這樣你就還沒有結束的跡象,但它的工作幾乎相同的方式。

// everytime some option is selected in the select with "cars" id 
 
$('#cars').on('change', function() { 
 
    // it will run through the selected options 
 
    $('option:selected').each(function() { 
 
     var op = $(this); 
 
     var text = op.text(); 
 
     
 
     // checks if the button is already there 
 
     var already_there = false; 
 
     $('#btns button').each(function() { 
 
      var btn = $(this); 
 
      if(btn.text() == op.text()) { 
 
       already_there = true; 
 
       // leaves the verification 
 
       return false; 
 
      } 
 
     }); 
 
     
 
     // if it isn't, appends to the div with id "btns" 
 
     if(!already_there) { 
 
      var btn = $('<button type="button" class="btn btn-default" onclick="removeBtn(this)"></button>'); 
 
      btn.append(text); 
 
      
 
      $('#btns').append(btn); 
 
     } 
 
    }); 
 
      
 
}); 
 

 
// removes a button (obvious xD) 
 
function removeBtn(btn) { 
 
    $(btn).remove(); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<html> 
 
<head><title>Test</title></head> 
 
<body> 
 
<select multiple id="cars"> 
 
    <option value="volvo">Volvo</option> 
 
    <option value="saab">Saab</option> 
 
    <option value="fiat">Fiat</option> 
 
    <option value="audi">Audi</option> 
 
</select> 
 

 
<div id="btns"></div> 
 

 
</body> 
 
</html>

+0

我有一個問題,請在你的解決方案,當我添加一個選項,然後刪除它,然後我想再次添加它我不能那樣做,你能解決它嗎? – stephjhonny