将按钮操作添加到输入类型搜索



我有一个带有搜索栏的小部件。我想添加一个按钮,在点击时进行搜索操作。这是我的HTML,我尝试过但没有成功:--当我点击search-bar-button按钮时,我会收到一条Undefined消息——

php

<form role="search" method="get" class="searchform" action="http://website.test/">
<label for="terrain-search-form-1">
<span class="screen-reader-text">Search:</span>
<input type="search" id="terrain-search-form-1" class="field" autocomplete="off" placeholder="Search" name="s">
</label>
<input type="hidden" name="lang" value="es">
</form>
<a id="search-bar-button" javascript="void(0)"></a>

js

document.getElementById("search-bar-button").addEventListener("click", function(){
document.getElementById("terrain-search-form-1").value = this.value;
});

如果您想将按钮的文本设置为搜索值,请使用:

document.getElementById("terrain-search-form-1").value = this.innerText

如果您想将按钮中的属性值作为搜索值,请使用:

document.getElementById("terrain-search-form-1").value = this.getAttribute("id");
//this will set the search value to 'search-bar-button'

最终,要提交带有值的表单,请使用:

document.querySelector(".searchform").submit();

最新更新