jQuery - 如果任何div中的选择有一个值 [英] jQuery - If ANY Select within a div has a value
问题描述
这个问题一直很麻烦。假设我有以下html:
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>
我有很多这些,所以我想做的就是如果有任何选择则返回false '具有'Select One'的价值,然后提醒他们。到目前为止我的jQuery看起来如此:
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! :)
推荐答案
$('#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();
}
});
示例: http://jsfiddle.net/raj_er04/3kHVY/1/
快速注意:如果您只想要提醒每次'select one'显示一次而不是一次,只需将alert()移动到else {语句中。再次感谢您的回答!
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!
这篇关于jQuery - 如果任何div中的选择有一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!