HTML-按钮-在搜索栏中单击

时间:2018-10-24 12:16:46

标签: javascript html button onclick

我正在寻找以下解决方案:我有一个带有以下代码的搜索栏:

<input autofocus class="form-control" style="width:40%" type="search" id="myInput" placeholder="Enter keywords here...">

我有几个这样的按钮:

<input type="button" value="Banana">
<input type="button" value="Pear">

我需要按顺序添加什么,因此,当您单击“香蕉”按钮时,在搜索栏中粘贴了“香蕉”一词(输入id =“ myInput”)。

我知道您需要在按钮输入中使用onclick =“”并使用Javascript粘贴文本,但是功能是什么?

编辑:

我目前已经有一个监听器事件:

 document.addEventListener('DOMContentLoaded', function() {
  if (document.getElementById("myInput").value.length > 1) {
    document.getElementById("header").className = "hideHeader";
  } else {
    ContactsearchFX();
    document.getElementById('myInput').addEventListener('input', ContactsearchFX);
  }
});

我如何集成此解决方案:

HTML

<button onclick="addval('Banana')">Banana</button>
<button onClick="addval('Pear')">Pear</button>

JavaScript

 function setValue(name){
   document.getElementById("myInput").value = name;

}

4 个答案:

答案 0 :(得分:2)

您需要将按钮的值添加到输入文本中。 首先,您创建一个函数来处理按钮的单击,完成后,将按钮的值传递到输入字段。

const clickButtonHandler = (evt) => { 
 document.querySelector('.form-control').value = evt.value;
}
<input autofocus class="form-control" style="width:40%" type="search" id="myInput" placeholder="Enter keywords here...">

<input type="button" onclick="clickButtonHandler(this)" value="Banana">
<input type="button" onclick="clickButtonHandler(this)" value="Pear">

答案 1 :(得分:0)

我认为这可以解决此问题:

<input type="button" id="fruit" value="Banana">

document.getElementById("fruit").addEventListener("click", function(){
       document.getElementById("myInput").value = this.value;
});

答案 2 :(得分:0)

HTML

 <?xml version="1.0" encoding="utf-8"?>
    <shape android:shape="oval"
        xmlns:android="http://schemas.android.com/apk/res/android">
        <size android:width="40dp"
            android:height="40dp"/>
        <solid android:color="#FF88EE88"/>
        <stroke android:color="#FFEE8800" android:width="4dp"/>
    </shape>

JavaScript

<input autofocus class="form-control" style="width:40%" type="search" id="myInput" placeholder="Enter keywords here...">
<button onclick="addval('Banana')">Banana</button>
<button onClick="addval('Apple')">Apple</button>

答案 3 :(得分:0)

尝试以下操作:

function myFunction() {
   document.getElementById("myInput").value = "Banana";
}

对于按钮:

<button type="button" onclick="myFunction()">Banana</button>