Reputation: 5980
I am writing a plugin for WordPress and am confused as to how to compare the user-input (got from an <input>
element) to a set of <option>
elements in a <select>
element.
At the moment I am doing the following:
$('button#test_button').click(function(event) {
event.preventDefault();
// Get the text in the input box:
var input_text = $('input#input_test').text();
$("#selectId > option").each(function() {
if ($(this).text() == input_text) {
alert("Alert Triggered");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="input_test"></input>
<select id="selectId">
<option value="hello">Foo</option>
<option value="test">Test</option>
</select>
<button id="test_button">Click me!</button>
However, if you run the snippet you can see that the alert is never triggered, but I'm not sure why? I'm new to JavaScript so I'm not aware of any intricacies to the language, so this is probably a simple query, but I'd be grateful for any assistance.
Upvotes: 0
Views: 51
Reputation: 27765
You need to use val()
method to get input value. And you have a typo of getting text content of <option>
tag. Should be $(this).text()
, not $(this).text
$('button#test_button').click( function(event) {
event.preventDefault();
// Get the text in the input box:
var input_text = $('input#input_test').val();
$("#selectId > option").each(function() {
if( $(this).text() == input_text )
{
alert("Alert Triggered");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="input_test"></input>
<select id="selectId">
<option value="hello">Foo</option>
<option value="test">Test</option>
</select>
<button id="test_button">Click me!</button>
Upvotes: 1