【问题标题】:display current alert when change select value更改选择值时显示当前警报
【发布时间】:2022-07-01 21:12:02
【问题描述】:

我有一个选择(下拉)和一个输入。当我在输入时输入一个数字时,选择使用该数字更改的值:

<input id="input" type="text" name="selectChanger">

<select id="select">
  <option value="" selected></option>
  <option value="0">floor 0</option>
  <option value="1">floor 1</option>
  <option value="2">floor 2</option>
</select>

我想在更改选择值时显示警报:

document.getElementById('input').addEventListener('input', function (event){
    let de = new Event('change');
    document.getElementById('select').dispatchEvent(de);
    document.getElementById('select').value = document.getElementById('input').value;
})

document.getElementById('select').addEventListener('change', function (event){
    alert(document.getElementById('select').text + ' was selected.')
})

现在输入数字0时显示 was selected,然后输入数字1显示floor 0 was selected但必须显示floor 1 was selected

我该如何解决这个问题?

【问题讨论】:

    标签: javascript


    【解决方案1】:

    我想这会对你有所帮助。

    //First Way
    
    document.addEventListener('DOMContentLoaded', event => {
      const target_input  = document.querySelector('#input'),
            target_select = document.querySelector('#select');
    
      if (target_input != null) {
        target_input.addEventListener('input', event => {
            const { target } = event;
    
            for (const node of [...target_select.childNodes]) {
                if (node.nodeType == 1) {
                    if (node.value == target.value) {
                    node.selected = true;
                    alert(`${node.textContent} is selected`)
                    break;
                  }
                }
            
            }
        })
      }
    });
    // Second way
    
    const {input, select} = {input: document.getElementById('input'), select: document.getElementById('select')};
    
    input.addEventListener('input', function (event){
       const selector = select.querySelector(`option[value="${input.value}"]`);
       if (selector == null) {
            alert('Does not exist!'); 
          return '';
       }
        selector.selected = true;
        select.dispatchEvent(new Event('change'));
    })
    
    select.addEventListener('change', function (event){
        alert(select.value + ' was selected.')
    })
    <input id="input" type="text" name="selectChanger">
    <select id="select">
        <option value="" selected></option>
        <option value="0">floor 0</option>
        <option value="1">floor 1</option>
        <option value="2">floor 2</option>
    </select>

    【讨论】:

    • 谢谢,但我想用两个 EventListener 。我的真实代码很复杂,我问一个简单的代码。
    • 你的版本不好,不能那样做。如果你想使用带有 2 个事件的版本,你应该按照我在答案中编辑的那样做
    猜你喜欢
    • 2015-07-28
    • 2021-12-22
    • 1970-01-01
    • 2015-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-03
    • 1970-01-01
    相关资源
    最近更新 更多