AJGreene
AJGreene

Reputation: 33

Submitting form with enter button in Ajax

My issue is that when I click my button, it will work properly, but if I use the enter button, it will attempt to submit the form and appends a ?var=x to the URL.

My two inputs:

    <input type="text" name="users" onkeydown="if (event.keyCode == 13) document.getElementById('submitbtn').click()">
    <input type="button" name="submitbtn" onclick="showUser(users.value)">

You may view my source for the rest. If you put in 1 or 2 and click the button, you will get results, but if you hit enter, it will not give you results and changes the URL as I said.

http://crystalarcade.com/shoutbox

Upvotes: 1

Views: 2863

Answers (2)

hyde
hyde

Reputation: 2585

I am assuming you will have a form with just two input elements. With jQuery you can do something like this:

Some thing like this should get you started with, I need make a note however that this code is untested because I cannot do cross-site request using AJAX.

<script type="text/javascript">
$(function(){
    $("#username").on("keypress", function(e){
       if(e.keyCode==13){ //keyCode value of 13 is for the enter key
        $.get("getusers.php" $("#userSearchForm").serialize(), function(data){
            if(data){
              $("shoutboxtxt").text(data);      
            }                
        }, "text");
    }
  }
});​
</script>

<form id="userSearchForm">
    <input type="text" name="users" id="username" />
    <input type="button" name="submitbtn" id="submitbtn" value="Search" />
</form>

<div id="shoutboxtxt"><b>Person info will be listed here.</b></div>​

Online here: http://jsfiddle.net/HwcN3/1/

Upvotes: 0

rahul
rahul

Reputation: 7663

you are using document.getElementById so give your button an id

like this

<input type="text" name="users" onkeydown="if (event.keyCode == 13) document.getElementById('submitbtn').click()">
<input type="button" id="submitbtn" name="submitbtn" onclick="showUser(users.value)">

and this will work for you

Upvotes: 4

Related Questions