【问题标题】:Field Selection on input输入字段选择
【发布时间】:2019-02-08 10:55:41
【问题描述】:

我在 PHP/HTML 中的输入/选择字段有问题。如果用户在输入字段中写入数字,则选择框应自动选择该值。我想我可以用事件监听器 onchange 解决这个问题,但我不确定如何。

<select id="name" name="name" style="width: 154px"  /><br />
            <optgroup label="Department1">
            <option value="John">John</option>
            <option value="Max">Max</option>
            <option value="Test">Test</option>
             </optgroup>
            </select><br />
            </label>
            </td>
        </tr>
        <tr>
            <td>Number*: </td>
            <td>
            <input id="number" name="number" type="text" value="" maxlength="5" required style="width: 154px"/><br />
            </td>
        </tr>
        <tr>

【问题讨论】:

  • 数字和应该选择的值是什么关系?
  • 您想要纯 JavaScript 解决方案,还是使用框架?

标签: javascript php html forms event-handling


【解决方案1】:

在 codepen 中试试这个:

const  selectBoxField = document.getElementById('name')
const fieldNumber = document.getElementById('number')

fieldNumber.addEventListener('keyup', ({target}) => {
  selectBoxField.selectedIndex = target.value-1;
});
// variant with Id's
fieldNumber.addEventListener('keyup', ({target}) => {  
  const index = Array.from(selectBoxField).findIndex(option => option.id === target.value);
  selectBoxField.selectedIndex = index; 
});

在此处查看工作示例https://codepen.io/kurkov87/pen/daJBpa?editors=1111

【讨论】:

  • 谢谢。你的代码几乎是我需要的。您现在是否可以为选择框名称分配特定值,例如比如如果你写数字 12345 John 会被选中,而 13455 Max 会被选中?
  • @D2a 你可以看看这个重写示例codepen.io/kurkov87/pen/daJBpa?editors=1011
【解决方案2】:

在 onblur 中调用事件.. 我相信它会起作用

我给你一个简单的例子


    <select name="" id="asd">
        <option value="ashir">ashir</option>
        <option value="haroon">haroon</option>
    </select>

    <input type="text" id="input_id" onblur="func()">

JS 代码

function func(){
        var input_id = document.getElementById('input_id').value;
        document.getElementById('asd').value = input_id;
    }

【讨论】:

    【解决方案3】:

    第一件事“onchange”事件在 HTML 的文本字段中不可用,您可以像这样使用“onkeyup”事件:-

    document.getElementById('number').addEventListener('keyup',(event) => {
        let num = parseInt(event.target.value);
        // write here the code to select the right option in drop down
    });
    

    【讨论】:

      猜你喜欢
      • 2012-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多