【问题标题】:javascript: form select option and input fieldjavascript:表单选择选项和输入字段
【发布时间】:2012-10-22 05:52:27
【问题描述】:

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

<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' />

我像这样从input 获得值:

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

但我无法从动态表单select 中选择选项

document.form.formsel.value = input_val;

谁能看出我做错了什么?

【问题讨论】:

  • jQuery 扭曲了我——我能想到的只有$("#formsel option:selected").text()
  • 酷 - 在这种情况下作为答案发布。

标签: javascript forms select option


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    这应该可以得到你想要的

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

    【讨论】:

    • 除非他的意思是别的,他要求的是相反的,想要根据输入的文本选择值,而不是从选择列表中获取值。尽管他对您的评论的回应表明这是正确的答案。喂。
    【解决方案3】:

    看来您可能有错字。

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

    应该是:

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

    【讨论】:

    • 即便如此,这也解决不了这个问题。
    【解决方案4】:

    试试这个:

    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;
    
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-14
      • 2015-09-26
      • 1970-01-01
      • 1970-01-01
      • 2018-08-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多