I'm struggling with looping through options within a form select. The options are grouped into optgroups, and I believe this is where my issue lies as I can't seem to find the correct syntax.
My objective is to compare the value entered using .val()
with the text of the options in the list using .text()
. If there is a match, I want to change the text color to red; if not, turn it green.
When I input an invalid id instead of sreportname
here: $("#sreportname option")
, the text always turns green. However, when I use sreportname
, nothing happens. I'm stuck at this point.
Here is the structure of my form:
<form>
<select name="sreportname" id="sreportname" class="form-control">
<option value="zrxqy">--Choose a Report--</option>
<option value="newReport">--Create a New Report--</option>
<optgroup label="General Reports">
<option>Abandoned Mines</option>
</optgroup>
<optgroup label="TPS Reports">
<option>Farm</option>
<option>Store</option>
<option>Chicken Coops</option>
</optgroup>
</select>
<input type="text" id="newReportName" name="newReportName">
</form>
And here is the jQuery code:
$(document).ready(function () {
var exists = false;
$("#newReportName").keyup(function () {
$("#sreportname option").each(function () {
if ($(this).text() == content) {
exists = true;
return false;
}
});
if(exists) {
$(this).css("color", "red");
} else {
$(this).css("color", "green");
}
});
});
I have put together a live example. Any suggestions would be greatly appreciated.