Reputation: 2082
I need a way to loop through all options in a dropdown list via code, and compare each one to a variable. if they match, i want make the matching value be the item that is selected in the dropdown, and then exit the loop. So far, this is what I've come up with ... which works as far as looping the items is concerned.
$("#domains > option").each(function() {
if (edit_domain[1] == $(this).val()) {
//assign this as being the selected value in dropdown
//exit loop
}
});
EDIT 1
I changed my code to look like the following:
//loop through values in drop down to see if we find a match
$("#domain option").each(function() {
var $this=$(this);
alert($(this).val());
if ($this.val() == edit_domain[1] ) {
console.log("compared");
$("#prefix").val(edit_domain[0]);
$("#domain").val(edit_domain[1]);
}
});
When I refresh my page, I don't get any error messages, but none of the logic inside the loop seems to work. No alerts, no messages in the console. As a test I opened up the debug tools via F12. In the console, I manually typed in the following command:
$("#domain option").each(function() {
alert($(this).val());
});
It properly returns all values from my drop down box. I'm not sure where in the code I've gone wrong! Interestingly, when I test in IE, I do see the following error message about the line of HTML code where I declare / create the dropdown box:
HTML1402: Character reference is missing an ending semicolon ";".
And the HTML code looks like this:
<tr><td width="30%">Cell Carrier: (e.g.AT&T)</td><td><select class="form-control" name=domain id=domain></select></td></tr>
Could this be an issue? If my html was bad, I don't think my ajax code that queries the database and then populates the drop down would work at all. But it does... It's just the logic that queries the values in the drop down after it's been populated that's failing.
Upvotes: 0
Views: 4778
Reputation: 1
You can use the below function to compare to option value with the variable.
$(document).ready(function(){
$('select option').each(function(){
var $this = $(this);
if($this.val() == variableValue){
alert('compared');
exit;
}
});
});
Upvotes: 0
Reputation: 17481
You can also do something like this:
$("#domains option").filter(function() {
return ($(this).val() == edit_domain[1]);
}).prop('selected', true);
Upvotes: 0
Reputation: 272306
When using jQuery, you can use the .val()
function for this:
$("#domains").val(edit_domain[1]);
Upvotes: 3