我正在为WordPress编写一个插件,并且对如何将用户输入(从<input>
元素获得)与<option>
中的一组<select>
元素进行比较感到困惑元件。
目前我正在做以下事情:
$('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>
但是,如果您运行代码段,您可以看到警报从未被触发,但我不确定为什么?我是JavaScript的新手,所以我不知道该语言的任何复杂性,所以这可能是一个简单的查询,但我会感激任何帮助。
答案 0 :(得分:1)
您需要使用val()
方法来获取输入值。你有一个错误的获取<option>
标签的文本内容。应该是$(this).text()
,而不是$(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");
}
});
});
&#13;
<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>
&#13;