javascript:表单选择选项和输入字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13180537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:00:40  来源:igfitidea点击:

javascript: form select option and input field

javascriptformsselectoption

提问by JasperM

I have an form inputfield, when a user types "text 2", I want that "text 2" selected in the form select:

我有一个表单input字段,当用户输入“text 2”时,我希望在表单中选择“text 2” select

<select id="formsel">
    <option value="text 1">text 1</option>
    <option value="text 3">text 2</option>
    <option value="text 3">text 3</option>
</select>
<input type='text' id='input' />

I get the value from the inputlike this:

我从input这样的价值中得到:

var input_val = document.getElementById('input').value; 

But I can not select the option from the dynamic form selectwith

但我不能选择从动态表单的选项select

document.form.formsel.value = input_val;

Can anyone see what I'm doing wrong?

谁能看到我做错了什么?

采纳答案by Adam Rackis

Based on your comment, it looks like you're using jQuery (you should tag all questions with jQuery if that's the case).

根据您的评论,您似乎正在使用 jQuery(如果是这种情况,您应该使用 jQuery 标记所有问题)。

This should get you what you want

这应该让你得到你想要的

var selectedText = $("#formsel option:selected").text()

回答by Armon

Your code doesn't show the formyou are trying to access with document.form, so I'm assuming there is no form. Try accessing the selectby its id. This seems to work for me:

您的代码未显示form您尝试使用 访问的内容document.form,因此我假设没有表单。尝试select通过其 ID访问。这似乎对我有用:

<script>
document.getElementById('input').onkeyup = function()
{
    var input_val = document.getElementById('input').value;
    document.getElementById('formsel').value = input_val;
}
</script>

回答by 0x499602D2

Try this:

试试这个:

var nodes = document.getElementById('formsel'),
    txt = document.getElementById('input').value, node;

for ( var i = nodes.length; i--; ) {

    node = nodes[i];

    if ( txt === nodes[i].value ) {

        node.selected = true; break;

    }

}

回答by skrieder

It looks like you might have a typo.

看起来你可能有一个错字。

<option value="text 3">text 2</option>

Should be:

应该:

<option value="text 2">text 2</option>