【问题标题】:How to link a button and input field如何链接按钮和输入字段
【发布时间】:2021-10-22 22:17:45
【问题描述】:

如何将按钮链接到输入字段?我正在尝试创建一些东西,以便当我单击按钮时,它会将文本字段中的内容添加到数组中(如下所示)

const userTags = [];
function addTags(event) {
   userTags.push(event.target.__ what do I even put here to get the input data? __)
}

<label>
   Tags: <input type="text" name="todoTags"/> <button>Create new tag</button>
</label>

我再次尝试链接按钮,以便当我单击它时,它会从输入字段中获取数据,并使用 addTags() 函数将该数据添加到“userTag”数组中。

【问题讨论】:

    标签: javascript html css forms form-submit


    【解决方案1】:

    let valueArray = []
    function getValue(){
    let value = document.getElementById("input").value
    valueArray.push(value)
    document.getElementById("Messages").innerHTML = valueArray
    }
    <body>
    <input type="text" id="input">
    <button onclick="getValue()">Click</button>
    <div id="Messages"></div>
    </body>

    用 document.getElementById 获取元素,然后取其值

    document.getElementById("Put Id In Here").value
    

    【讨论】:

      【解决方案2】:

      您可以在回调函数中使用事件目标通过const parent = e.target.closest('label') 获取标签,然后使用querySelector() 通过const input = parent.querySelector('input') 获取分组在该标签标签下的输入元素然后将变量设置为该值,例如const inputValue = input.value,然后将该值推送到您的数组中。

      你的回调函数被放置在一个点击事件监听器中。

      const btn = document.querySelector('.btn')
      const userTags = []
      
      function getValue(e) {
        // get the label by traversing up the DOM tree to the closest label element
        const parent = e.target.closest('label')
        // get the input that lives inside the label element using querySelector
        const input = parent.querySelector('input')
        // get the inputs value and assign to variable
        const inputValue = input.value
        // only push values that are not empty
        if (inputValue !== "") {
          userTags.push(inputValue)
        }
        console.log(userTags)
      }
      
      //event listener for click on btn element
      btn.addEventListener('click', getValue)
      <label>
         Tags: <input type="text" name="todoTags"/> <button class="btn">Create new tag</button>
      </label>

      【讨论】:

      • 嘿!我不断收到“TypeError: Cannot read property 'addEventListener' of null”错误,我想我可能知道原因。我正在使用 React,所以我在“return()”块中创建类。是否有可能我需要以某种方式在 return 语句中添加事件侦听器?或者您知道为什么我不断收到“事件侦听器为空错误”吗?顺便说一句,感谢您的回复!
      • 对不起,我不熟悉 REACT。也许您可以在答案中添加相关代码并编辑问题?我会看看它,看看我是否能弄清楚。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-18
      • 2018-08-09
      • 1970-01-01
      • 2012-03-02
      • 2011-10-04
      • 1970-01-01
      相关资源
      最近更新 更多