简体   繁体   中英

Make function available onClick and onKeypress JQuery/Javascript?

I would like to make my function available for user if they click on the button but if they press enter as well. Here is example:

 $('#searchBtn').on('click', function searchUser(){ $.ajax({ type: 'POST', url: 'Components/Application.cfc?method=findUser', data: {'searchFldVal':searchFldVal}, dataType: 'json' }).done(function(obj){ return true; }else{ return false; } }); return false; } }).fail(function(jqXHR, textStatus, errorThrown){ alert(errorThrown); }); } }); 
 <form name="searchForm" id="searchForm" action="#" method="POST" onsubmit="searchUser()"> <div> <input type="text" name="searchFld" id="searchFld" size="24" maxlength="24" value="" title="Maximum size of the field is 24 characters." placeholder="Example: John, Miller" /> </div> <div> <input type="button" name="searchBtn" id="searchBtn" value="Search"/> </div> </form> 

Code above works fine if I click on button but if I enter few letters and press enter my page will reload. This file is saved as .cfm file. I would like to run searchUser() function on both onClick and onKeypress . If anyone knows how this can be achieved please let me know.

Since you're using jQuery, do not use inline event handlers. Define the function and call it when the form is being submitted as below:

 function searchUser(e) { e.preventDefault(); alert ("Do your ajax here instead of alert..."); } $("#searchForm").on("submit", searchUser); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form name="searchForm" id="searchForm" action="#" method="POST"> <div> <input type="text" name="searchFld" id="searchFld" size="24" maxlength="24" value="" title="Maximum size of the field is 24 characters." placeholder="Example: John, Miller" /> </div> <div> <input type="submit" name="searchBtn" id="searchBtn" value="Search"/> </div> </form> 

Note:

  • removed inline event handler from the form
  • changed button type to submit.

If you are using AJAX to communicate with your server, you might want to leave the method, action, and submit callback off of the form entirely. This is what will cause the default submit behavior of the page reload. Instead, attach a listener to the search field itself, that listens for the enter key press.

$('#searchBtn').on('click', searchUser);

$('#searchFld').on('keypress', function(e){
    e.preventDefault();
    if(e.code == 'Enter'){
         searchUser();
    }
}); 


function searchUser(){
    // search for the user
}

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