2013-08-30 53 views
0

我正在一個Web應用程序,我在一個頁面中有兩個下拉菜單。JQuery/Javascript檢查下拉列表

<div id="A"> 
<select> 
    <option value="">please select</option> 
    <option>1</option> 
    <option>2</option> 
    <option>3</option> 
    <option>4</option> 
    <option>5</option> 
</select> 
<select> 
    <option value="">please select</option> 
    <option>6</option> 
    <option>7</option> 
    <option>8</option> 
    <option>9</option> 
    <option>10</option> 
</select> 
</div> 

現在,我想使這兩個下拉強制進行選擇(從「請選擇」分開),或用戶傾斜再往前走。 這裏是我的jQuery代碼。

 var error=0; 
     var selected_option = $('#A>select option:selected'); 
     $('#A').each(function() { 
      if(!$('#A select').selected){ 
       error++; 
      } 
     }); 
     if (error>0) { 
      alert('Choose the bloody option'); 
      return false; 
     } 

到目前爲止,實際結果是警報消息工作正常,強制性選擇部分工作正常。然而,即使我從兩者中選擇,我仍然有警覺和卡住。想想也許是我的if condition設置不當。請,有人給我一個幫助。非常感謝你。

回答

2

更改爲val()選擇的值以獲取select的值。

if(!$('#A select').val()){ 
+0

將無法​​工作,因爲有多個選擇元素...它只會檢查第一個元素lect元素 –

1

嘗試

var valid = $('#A select').filter(function(){ 
    return $.trim($(this).val()) == '' 
}).length == 0 

if(!valid){ 
    alert('not selected') 
} 

演示:Fiddle

另一個版本

if ($('#A select').has('option:selected[value=""]').length > 0) { 
    console.error('not selected') 
}else { 
    console.log('valid') 
} 

演示:Fiddle

1

你可以在這裏試試我這一個另外一種方式來實現你想要

$('#A select').each(function() { 
    if(this.options[this.selectedIndex].value != 'please select'){ 
     //do here your action 
    } 
} 
1

試試這個什麼:

$('#A select').each(function() { 
     if($(this).find('option:selected').text() == 'please select'){ 
     error++; 
     } 
    }); 
+0

將無法​​工作,因爲有多個選擇元素...它只會檢查第一個選擇元素 –

1

DEMO

var selected_option = $('#A>select option:selected'); 
$('#check').click(function() { 
    var error = 0; 
    $('#A select').each(function() { 
     if ($(this).val() == '') { 
      error++; 
     } 
    }); 
    if (error > 0) { 
     alert('Choose the bloody option'); 
     return false; 
    } 
}); 
1

你可以嘗試:

var errors = 0; 
$("#A select").each(function(){ 
if($(this).find("option:selected").is(":eq(0)")){ 
     errors++; 
} 
}); 

if(errors>0){ alert('error!'); }