开发者

submit text field on enter press (AJAX)

开发者 https://www.devze.com 2022-12-19 07:41 出处:网络
I have a search that operates by AJAX. It works perfectly well when the user presses the search button, the problem is... if the user presses enter... it submit the form rather than executing the AJAX

I have a search that operates by AJAX. It works perfectly well when the user presses the search button, the problem is... if the user presses enter... it submit the form rather than executing the AJAX javascript function. How can I make the Enter button call my AJAX function a开发者_如何学运维s opposed to submitting the form?


Use the form's onsubmit event to execute your ajax call and make the button into a submit button if it isn't already.

Example HTML

<form action="/search.php" onsubmit="submitAjaxQuery(event)">
    <input type="text" name="keywords" />
    <button type="submit">Go!</button>
</form>

Example JS

function submitAjaxQuery(event)
{
    if (event.preventDefault)
        event.preventDefault();
    else
        event.cancel = true;

    // run ajax calling function here.
}


Here is a simple DOM way to handle this:

<form action="javascript:void(0)">
    <input type="text" />
    <input type="submit" onclick="doSomething(this.form)">  
</form>
<script>
    function doSomething(form){
        alert('form submitted');
    }
</script>

Place the cursor in the input field, and either if you click the button or type enter, the form is submitted by javascript (not the page)


Trap it in the onSubmit method of the form and return false.


With jQuery:

jQuery("#myform").submit(function() {
 callAJAXFunction();
 return false;
});


The correct way is to let the non-javascript users use the form submit with page refresh but a javascript call for those with javascript:

<form action="yourscript.php" method="post" onsubmit="doSomething(this.form); return false;">
    <input type="text" />
    <input type="submit" />  
</form>
<script>
    function doSomething(form){
        alert('form submitted');
    }
</script>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号