简体   繁体   中英

Search using enter key and search button JavaScript

I'm using the following code and it works fine by clicking on the search button. But how can I also search using the enter key?

Code:

 <script> function mySearch() { var text = document.getElementById('strSearchText').value; var url = "privatelink=" + text; window.open(url,'_blank'); } </script> 
 <style> button:hover {color:red;} .rounded-corners { -moz-border-radius: 20px; -webkit-border-radius: 20px; -khtml-border-radius: 20px; border-radius: 20px; white-space:normal; font-weight:bold; width: 50%; } .smallbutton { -moz-border-radius: 20px; -webkit-border-radius: 20px; -khtml-border-radius: 20px; border-radius: 20px; white-space:normal; font-weight:bold; width: 20%; } </style> 
 <br> <input type="text" size="25" tabindex="1" value="" id="strSearchText">&nbsp; <button class="smallbutton" onclick="mySearch();"><span style="DISPLAY: inline-block">Search</span></button> 

Stick it in a form, and it does that by default

<form id="myform">
    <input type="text" size="25" tabindex="1" value="" id="strSearchText">
    <button class="smallbutton">
        <span style="display: inline-block">Search</span>
    </button>
</form>

and then

var form = document.getElementById('myform')

form.addEventListener('submit', function() {
  var text = document.getElementById('strSearchText').value;
  var url  = "privatelink=" + text;

  window.open(url,'_blank');
}, false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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