2012-09-21 60 views
-4

可能重複:
Check if option is selected with jQuery, if not select a default檢查選項被選中

我有HTML這樣的:

<div id="somedivid"> 

<select class="someclass"> 
<!-- options --> 
</select> 

<select class="someclass"> 
<!-- options --> 
</select> 

</div> 

如果兩個選擇框,選擇選項如何檢查?

編輯:我不能改變HTML,所以它意味着我不能添加ID來選擇元素。

+1

我所做的就是寫你的問題的話題+「jQuery的」谷歌和[看我找到了什麼(HTTP ://stackoverflow.com/questions/149573/check-if-option-is-selected-with-jquery-if-not-select-a-default) – Tom

+0

@湯姆,你找到解決方案時,只有一個選擇元素。我知道該怎麼做。 – SomeoneS

回答

2

選擇始終有一個選擇。

但假如你把一個空的選擇是這樣的:

​<select id=select1> 
    <option></option> 
    <option>A</option> 
    <option>B</option> 
</select>​ 

您可以測試:

if ($('#select1').val() && $('#select2').val()) { 
    // both have selection 

編輯:如果你沒有ID或名稱,你可以使用這個:

var allSelected = true: 
$('#somedivid select').each(function() { 
    if (!$(this).val()) { 
     allSelected = false; 
     break; 
    } 
}); 
+0

是的,我知道這樣做,但我選擇的元素沒有ID,只有兩個元素相同的類。而我不能改變HTML。 – SomeoneS

+0

如果您沒有ID或名稱,我編輯瞭解決方案。但是你必須定義什麼意思是選擇了某些東西(例如空的選擇)。 –

0
<script type="text/javascript"> 
    $(function() { 
     $('#somedivid > select').bind('change', function(){ 
      if($('#sel1').attr('value') != 'default' && $('#sel1').attr('value') != 'default'){ 
       //do something here. 
      } 
     }); 
    }); 
</script> 
<div id="somedivid"> 

    <select id="sel1"> 
     <option value="default" selected="selected"></option> 
     <!-- options --> 
    </select> 

    <select id="sel2"> 
     <option value="default" selected="selected"></option> 
     <!-- options --> 
    </select> 

</div> 
0

考慮機器人^ h選擇框有一些默認選項值=「無」

var isBothSelected=0; 
if($('#selectbox1 option:selected').val() =='none'){ 
    alert('Plase select the select1'); 
    isBothSelected=isBothSelected+1; 
    //return false; 
} 
if($('#selectbox2 option:selected').val() =='none'){ 
    alert('Plase select the select2'); 
    isBothSelected=isBothSelected+1; 
    // return false; 
} 
if(isBothSelected ==2){ 
    alert('Both are not selected') 
} 
0

試試這個

 var val= $("#selectid option:selected").value(); 
      if(val==="") 
       { 
      alert("your code on not selected condition"); 
      }