2013-08-30 22 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!'); }