Reputation: 549
Having trouble with this function. I can only make it work for the last dropdown option in select box. In other words, it only does what it's supposed to do if I type the text of the last option in select box. It doesn't recognize that I typed the other options. I do an alert in the each loop and it shows me all the options, and i also alert what i type in. It should work for all the options, but it's not. Trying to add or remove class on the text input box. If i type one of the options add error class. If i change what i type and it doesn't match any of the options, remove error class.
HTML:
<select id="select" class="select selectpicker input-block-level" name="select">
<option value="">pick a thing</option>
<option value="0.00">#1 thing</option>
<option value="0.01">1x1 thing</option>
<option value="0.02">some thing</option>
<option value="0.03">something</option>
<option value="0.04">thing</option>
</select>
<input id="text" class="span12" type="text" placeholder="type a thing" value="" name="text">
JS:
function getValue() {
var theValue = $('#text').val();
//alert(theValue);
//begin tried and failed stuff
//var exists = 0 != $('#select option[text='+thevalue+']').length;
//if($('#select option[text='+thevalue+']').length > 0)
//if(exists == true)
//{
//alert("exists");
//$("#text").addClass("error");
//} else {
//$("#text").removeClass("error");
//}
//end tried and failed stuff
$('#select option').each(function(){
var theDropValue = this.text.toLowerCase();
//alert (theDropValue);
var theNewValue = theValue.toLowerCase();
if (theDropValue == theNewValue) {
//exists = true;
$("#text").addClass("error");
} else {
$("#text").removeClass("error");
}
});
}
$(document.body).on( "change keyup input", "#text", function() {
getValue();
});
Upvotes: 0
Views: 875
Reputation: 518
that's because
$('#select option').each
loops all the items in the object and you have just 1 output that you override each time.
You see just last item working because last item override all the others.
Upvotes: 0
Reputation: 1654
In the for loop, if the value exists, add error
class and return
if (theDropValue == theNewValue) {
//exists = true;
$("#text").addClass("error");
return; // add this line
} else {
$("#text").removeClass("error");
}
Upvotes: 0
Reputation: 9691
The reason you only see the last one is because you never break out of the each loop. Once you find the value you need to return false;
so you stop checking against other values in the loop.
Fiddle: http://jsfiddle.net/3swv31px/
function getValue() {
var theValue = $('#text').val();
$('#select option').each(function () {
var theDropValue = this.text.toLowerCase();
//alert (theDropValue);
var theNewValue = theValue.toLowerCase();
if (theDropValue == theNewValue) {
//exists = true;
$("#text").addClass("error");
return false;
} else {
$("#text").removeClass("error");
}
});
}
$(document.body).on("change keyup input", "#text", function () {
getValue();
});
Upvotes: 1