简体   繁体   English

jQuery - 用于聚焦搜索框并模拟输入键的按钮

[英]jQuery - Button to focus a search box and simulate enter key

The idea here is when people click on "TEST" then it automatically populate the text input and do the search.这里的想法是当人们点击“测试”时,它会自动填充文本输入并进行搜索。 So I want to simulate Enter Key pressing when clicking on the text "TEST".所以我想在点击文本“TEST”时模拟按下 Enter 键。 Is there any ways to do with jQuery?有什么方法可以处理jQuery吗?

<div class="item" onclick="myFunc1()"><p onclick="myFunc2()">TEST</p></div>
    <script>
            function myFunc1() {
            document.getElementById("Search").value = "html templates";
            }
            function myFunc2() {
            document.getElementById("Search").focus();
            }
    </script>
    <input type="text" name="search" id="Search">
</div>

Here is a small demo based on your question and code:这是一个基于您的问题和代码的小演示:

 $("#testClickHere").on('click', function() { $("#Search").val($(this).text()).focus().trigger('keypress'); }); $("#Search").on('input keypress', function() { console.log($(this).val() + " is search string. Search code here..."); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="item"> <p id='testClickHere'>TEST</p> </div> <input type="text" name="search" id="Search">

The code you posted is hard to read due to poor spacing.由于间距不佳,您发布的代码难以阅读。 Also, why do you have the script tag inside of the div?另外,为什么在 div 中有 script 标签?

IMO, it would be better to use a button element than a paragraph element for the clicking of TEST. IMO,最好使用按钮元素而不是段落元素来单击 TEST。 Also, the myFunc1() is assigned to a div that does not have any visible styling which makes it difficult to click.此外,myFunc1() 被分配给一个没有任何可见样式的 div,这使得点击变得困难。

Did you add myFunc2() in order to assign text to the input?您是否添加了 myFunc2() 以便为输入分配文本? Could you explain more on its purpose?你能解释更多关于它的目的吗?

The code below does not do exactly what you requested but i think you can accomplish what you want based what's in it.下面的代码并不完全符合您的要求,但我认为您可以根据其中的内容完成您想要的操作。 Hope it helps.希望能帮助到你。

 var input = document.getElementById("my_input"); var button = document.getElementById("my_button"); input.onclick = fillInput; button.onclick = doSearch; function fillInput(){ input.value = "html templates"; } function doSearch(){ //search code here console.log("Searching..."); }
 <input id="my_input" type="text" placeholder="click here"> <button id="my_button">TEST</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM