如何根据输入的值自动选择选项
我需要根据输入的值在准备好的文档上实际选择 select 的选项。
示例:
<select id="mySelect">
<option value="1">myVal1</option>
<option value="2">myVal2</option>
</select>
<input type="text" id="myId" value="2">
例如,我们在页面加载时获得了输入的预定义值“2”。我需要自动选择选择框,其选项与输入“myId”具有相同的值。我的意思是必须选择“mayVal1”。
当输入没有值时,选择必须表现为默认。
谢谢!
I need select's option to be actually selected on document ready depending on an input's value.
Example:
<select id="mySelect">
<option value="1">myVal1</option>
<option value="2">myVal2</option>
</select>
<input type="text" id="myId" value="2">
For example, we've got a predefined value '2' of the input on page load. I need select-box to be auto-selected with it's option having the same value as input 'myId'. I mean 'mayVal1' must be selected.
When input has no value select must behave as default.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您提到的“文档准备就绪”有点表明您可能正在使用 jQuery,根据这一假设(尽管可能是错误的),我向您提供以下内容:
在 JS Fiddle 上进行演示。
编辑以回应OP的问题:
是的,考虑到您发布的示例和问题之间的差异,我将尝试解决这两种可能性。
首先,根据其文本组件(在上面的代码中,“myVal1”、“myVal2”位)选择一个
选项
:JS Fiddle demo:请注意,
option
元素的文本组件不 表示option
元素的值。其次,如果您想将
myId
输入元素中输入的值的第一部分链接到select
/的 value option
元素:JS Fiddle 演示。
这些演示可以与
keyup()
配合使用,或等效的操作/事件,但submit()
似乎是更好的选择。Your mention of "on document ready" sort of suggests that you might be using jQuery, with that assumption made (albeit perhaps erroneously), I offer you this:
With a demo at JS Fiddle.
Edited in response to OP's question:
Right, given the disparity between your posted example and your question, I'm going to try to address both of the possibilities.
First, to select an
option
based on its text component (in your above code, the 'myVal1','myVal2' bits):JS Fiddle demo: note that the text component of the
option
element does not represent the value of theoption
element.Secondly, if you want to link the first part of the value entered into the
myId
input element to the value of theselect
/option
element(s):JS Fiddle demo.
These demos could work with
keyup()
, or equivalent actions/events, butsubmit()
seemed the better choice.像下面这样的东西应该可以工作///
something like below should work///
在普通 JS 中:
使用 jQuery:
in vanilla JS:
with jQuery:
$('#mySelect').val('2').change();
$('#mySelect').val('2').change();