I have a form that has a few select dropdowns, and I want to make sure that at least one has the default of ‘0’ changed to something else. However, I can’t get my mind around how to do it. I’ve tried both .each() and a while statement, and neither behaves like I expect it to.
Here is the HTML:
<form>
<label>Qty:</label>
<select class="Qty">
<option selected="selected">0</option>
<option>1</option>
</select>
<br />
<label>Qty:</label>
<select class="Qty">
<option selected="selected">0</option>
<option>1</option>
</select>
<br />
<br />
<label>Qty:</label>
<select class="Qty">
<option selected="selected">0</option>
<option>1</option>
</select>
<br />
<a href="#">test</a>
</form>
and here is the while statement:
$(document).ready(function(){
$('a').click(function(e){
e.preventDefault();
while ($('select > option:selected').val()==0){
alert('hello');
}
});
Unless all the selects are set to something other than 0, it gets stuck in a loop where it keeps testing the selects (so the hello alert keeps coming up).
I tried each as well.
$('a').click(function(e){
e.preventDefault();
$('select > option:selected').each(function (i) {
if($(this).val()>0) {
alert('okay to proceed');
} else {
alert('nothing found');
}
});
});
This is a little better, but it keeps checking even after its found the true answer. So if I try to trigger an error message, it will say everything is okay but then trigger the error message still.
I also tried setting a variable for if its valid or not, but it keeps showing up as false:
$('a').click(function(e){
e.preventDefault();
var valid = false;
$('select > option:selected').each(function (i) {
if($(this).val()>0) {
var valid= true;
alert(valid);
}
});
if(valid==true) {
alert(valid);
alert('it works');
} else {
alert(valid);
alert('uh-oh');
}
});
I’m clearly missing something. Any assistance on this would be greatly appreciated.
In your first try, the
whilestatement, it will keep looping because:$('select > option:selected').val()will always==0and it never leaves the loop.For the
.eachyou can break the loop when it is found byreturn falseas mentioned in the documentation.For the last, you declare
varinside the.each(function()which means it is only defined within that function and as soon as it goes to the nexteachin the selection thevarwill be redefined — once it has exited the.eachit is no longer declared.So working off your last example: jsfiddle