簡體   English   中英

jQuery:如何檢查是否在選擇框中明確選擇了 NO 選項

[英]jQuery : How to check if NO option was explicitly selected in a select box

是否可以檢測在選擇框中是否沒有明確選擇任何選項?

我試過這些方法,但沒有一個有效:

<select id="mySelect">
  <option value="1">First</option>
  <option value="2">Second</option>
  <option value="3">Third</option>
  <option value="4">Fourth</option>
</select>

試驗 1:

alert($('#select option:selected').length); // returns 1

試驗 2:

alert($('#select option[selected=selected]').length); // returns 1

試驗 3:

alert($('#select option:selected').attr('selected')); // returns 'selected'

任何想法SO人?

嘗試這個:

<select id="mySelect">
  <option value="1">First</option>
  <option value="2">Second</option>
  <option value="3">Third</option>
  <option value="4">Fourth</option>
</select><input type="button" id="btncheck" value="check"/>

使用這個JS:

$('#btncheck').click(function(){
     if ($("#mySelect ")[0].selectedIndex <= 0) {
                alert("Not selected");
            }
    else
        alert("Selected");
});

它會檢查您的下拉菜單是否被選中。

試試這個小提琴: http : //jsfiddle.net/aPYyt/

希望有幫助!

PS:您必須將第一個值設為默認值。

這是一個普通的select 元素的工作原理:如果沒有其他選項設置了selected屬性,則選擇第一個選項。 最簡單的解決方法是添加一個選項作為第一個選項,如下所示:

<select id="mySelect">
  <option value="">-- select an item --</option>
  <option value="1">First</option>
  <option value="2">Second</option>
  <option value="3">Third</option>
  <option value="4">Fourth</option>
</select>

在 jQuery 中,您可以測試以下條件之一:

$("#mySelect").val() === "";
$("#mySelect option:selected").index() == 0;
$("#mySelect option:first:selected").length != 0;

選擇框總是有一個值。 如果您不手動更改默認值,您仍然有一個值。 為了檢查顯式更改,如您所說,您可以監視change

$('#select').change(function() { $(this).data('changed', true); });

那么你的條件是:

if(!!$('#select').data('changed')) { ... }

實現類似的更常見的方法是在頂部插入一個占位符值:

<option value="0">Please select one item</option>

...並測試

$('#select').val() == '0'

如果您需要找出 select 是否已從其原始值更改,即上面的測試,但要確保用戶沒有切換回默認值,您可以簡單地在頁面加載時存儲原始值:

$('#select').data('original-value', $('#select').val());

並檢查

$('#select').val() != $('#select').data('original-value');
var $inputs_select_options = $('option:selected');      

// remove empty(first option as default , value=="" ) options:
$inputs_select_options = $inputs_select_options.filter(function() {
    return this.value.length; //check by length value
});

默認情況下,索引 0 上的任何選項都被瀏覽器視為已選中。 問題的解決方案是在索引 0 處插入一個虛擬選項,在提交表單之前,您可以使用類似的方法驗證它

if($("#selectBox option").index("option:selected")>0) $("#myForm").submit();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM