问题
Been having lot's of trouble with this one. Let's say I had the following html:
<div id='step_1'>
<select name='select_1' id='choose'>
<option value='select one'>Select One</option>
<option value='yes'>Yes</option>
<option value='no'>No</option>
</select>
<select name='select_2' id='choose_again'>
<option value='select one'>Select One</option>
<option value='yes'>Yes</option>
<option value='no'>No</option>
</select>
<button id='submit'>button</button>
</div>
I have many of these, so what I'm trying to do is return false if ANY 'select' has the value of 'Select One' then alert them. The jQuery i have so far looks as so:
$('#submit').click(function() {
if ($('#step_1 select[value="select one"]').length() == 0) {
//succeed
} else {
alert('Please select yes or no!');
return false;
}
});
What am I doing wrong? Thanks in advance, I love this website! :)
回答1:
$('#submit').click(function(e) {
var flag = true;
$('select').each(function(){
if($(this).val() == "select one"){
alert("please select a value in " + $(this).attr("name"));
flag = false;
}
});
if(flag){
alert('perfect');
}else{
e.preventDefault();
}
});
EXAMPLE : http://jsfiddle.net/raj_er04/3kHVY/1/
Quick note: If you want the alert to only show once rather than once per each 'select one', simply move the alert() into the else{ statement. thanks again for this answer!
回答2:
You can do this with $.each():
$('#step_1').find('SELECT').each( function() {
if( $(this).val() === 'select one' ) {
alert('Please select yes or no!');
return false;
}
});
Note that returning false will prevent the loop from continuing once a missing field is found.
回答3:
Your test fails because length
is not a method. It is a property. Remove the ()
. If you look in your debugger you should see a warning about this.
Also, your selector should be checking the selected option, not the select list itself.
http://jsfiddle.net/7PPs4/
$('#submit').click(function() {
$foo = $('#step_1 select option:selected[value="select one"]');
alert($foo.length);
});
来源:https://stackoverflow.com/questions/8937227/jquery-if-any-select-within-a-div-has-a-value