2017-10-20 772 views
0

我有一個Bootstrap-Select下拉菜單,在將某個字符串輸入到文本輸入中時,它將從另一個源中填充。一切工作到第一個選項被默認選中的位置,我想阻止這個,所以用戶必須選擇一個選項。從Bootstrap-Select下拉組件中取消選擇任何選項

請在這裏看到一個演示:https://jsfiddle.net/moxxah8r/

代碼如下:

<style> 
    .form-control, 
    .selectpicker { 
    width: 220px; 
    } 

    #postalcode { 
    text-transform: uppercase; 
    margin-right: 10px; 
    } 
</style> 

<div style="padding: 10px;"> 
    <div style="display: flex;"> 
    <input name="postalcode" id="postalcode" type="text" class="form-control" autocomplete="postal-code"> 
    <select name="address" id="address" class="selectpicker" disabled> 
     <option value="0" selected>&nbsp;</option> 
    </select> 
    </div> 
</div> 

<script> 
    var data = ["1 Street Name", "2 Street Name", "3 Street Name", "4 Street Name", "5 Street Name"]; 
    $('#postalcode').on('input', function(e) { 
    var pattern = new RegExp('^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$'); 
    var text = $('#postalcode').val().toUpperCase(); 

    if (pattern.test(text)) { 
     $('#address').empty(); 
     $.each(data, function(i, value) { 
     $('#address').append($('<option>').text(value).attr('value', value)); 
     }); 
     $('#address option').prop('selected', false); 
     $('#address').prop('disabled', false); 
     $('#address').selectpicker('refresh'); 
    } else { 
     $('#address').empty().append('<option value="0" selected>&nbsp;</option>'); 
     $('#address').prop('disabled', true); 
     $('#address').selectpicker('refresh'); 
    } 
    }); 
</script> 
+0

只需添加一個空白選項,就像你在其他地方所做的那樣 – billyonecan

回答

2

你需要做的第一件事是從去除selected您預先定義<option>爲設計創造了問題,而不是默認。

而不是依靠空白<option>黑客,爲什麼不使用Bootstrap Select的一些內置功能?通過在<select>元素中指定title,您可以創建一個僞佔位符。這可以防止在下拉菜單中的第一項從默認被選中:

<select name="address" id="address" class="selectpicker" title="Make Your Selection" disabled>...</select>

你可以閱讀有關此功能以及在系統啓動選擇的自定義按鈕文本文檔等幾個標籤選項

https://silviomoreto.github.io/bootstrap-select/examples/#placeholder

+0

完美!定義一個標題做到了。即使設置title =「」也可以,因此在選擇某些內容之前不會顯示文本。謝謝!! – Reado

0

您可以用jQuery做到這一點。刪除所有空白選項標籤,並呼籲這對您的活動:

$('select#address').val([]); 
+0

對不起,但這沒有奏效。 – Reado

+1

我設置了一個小提琴來演示它的工作原理https://jsfiddle.net/973Lde7j/7/ – grusl83

+0

@ grusl83非常感謝!這是解決這個特殊問題的一個非常酷的方式,但它也解決了我的特殊問題。試圖用Bootstrap4清除單選按鈕,我不得不使用'.val([]);' –