进入触发按钮点击?

时间:2017-02-02 23:06:37

标签: javascript jquery html event-listener

我有一个像这样的html表单:

<form name="f1">
<center>
<strong>Search VMs:</strong> 
<input id='vms' name="word" type="text"  size="50" placeholder="Name or IP, space delimited, partial name OK."  autofocus autocomplete="off" pattern=".{3,}" required title="3 chars minimum"  /> in
<select name="vc" id='whichvc'>
    <option value="all" selected="selected">all VCs</option>
</select>
<input type="checkbox" id="check4detail" name="detail">Include details
<input name='searchbutton' value="Search VMs" type="button" onclick='xmlhttpPost("/cgi-bin/search-vm.pl")' />
<input value="Clear" type="button" onclick="clearBox('result')" />
</center>
</p>
<div id="loading"></div>
<div id="result"></div>
</form>

如您所见,有一个文本输入字段和一些其他按钮,其中一个按钮与其关联的onclick()侦听器。当用户输入文本并按Enter键时,如何触发该按钮上的onclick事件?

从论坛中尝试了这个解决方案,但它不知何故不起作用:

$('#vms').keypress(function(event){
if (event.which === 13){
$('#searchbutton').click();}
});

顺便说一句,当我在字段中输入文本并单击搜索按钮时,它工作得很好。但输入文字并按回车不会以某种方式触发搜索事件。

3 个答案:

答案 0 :(得分:1)

修改了@GolezTrol代码,以便输入文本字段上的onChange侦听器间接触发单击搜索按钮。

&#13;
&#13;
<form action="" method="get">
  Test field:
  <input type="text" name="test" onChange="aliasonclick">
  <br>
  <button name="searchbutton" id="clickthis" onclick="alert('it works!');">Submit</button>
  <button type="reset" value="Reset">Reset</button>
</form>

<script>
  function aliasonclick() {
    var searchbutton = document.getElementById("clickthis")
    searchbutton.click()
  }
</script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

将按钮类型更改为submit。在同一表单的其中一个编辑中按下按钮时,提交按钮会抓住回车键。在下面的示例中,您可以测试它。将光标放在编辑框中,然后按Enter键。你应该收到提醒。

<form action="" method="get" onsubmit="return false;">
Test field: <input type="text" name="test"><br>
<button type="submit" value="Submit" onclick="alert('it works!');">Submit</button>
<button type="reset" value="Reset">Reset</button>
</form>

请注意,这是一个浏览器实现细节。我不知道任何浏览器不能使用它,但同时我无法保证它可以在任何浏览器和任何平台上运行。

答案 2 :(得分:0)

$('#searchbutton').click();更改为$('#searchbutton').trigger('click');