3

I have

Html:

<form  action="" method="post"  id="contactForm">
    <input id='inputbox' name="inputbox" type="text" />
    <button type="button" id='search'> search </button>
</form>

JavaScript

$(document).ready(function() {
    $("#inputbox").keyup(function(event){
        if(event.keyCode == 13){
            $("#search").click();
        }
    });

    $('#search').click(function(){
         var inputbox= $("#inputbox").val();  
        //stuff
    });
});        

inputbox value is nothing when I press enter, however if I click on button It works perfectly with same input value

maybe making inputbox global?

Default
  • 14,844
  • 3
  • 23
  • 36
edgarmtze
  • 23,987
  • 75
  • 226
  • 373

1 Answers1

8

The problem is that the enter key defaults to submitting your form, even without a submit button. So you should block the submission by changing the event binding to keypress and using event.preventDefault(), like this:

$("#inputbox").keypress(function(event){
    if(event.keyCode == 13){
        event.preventDefault();
        $("#search").click();
    }
});

Alternatively, you could use .submit() to trigger your function, change the input type to submit, and avoid separate handling for keys and clicks.

HTML:

<form action="" method="post" id="contactForm">
    <input id='inputbox' name="inputbox" type="text" />
    <input type="submit" value="Search">
</form>

JavaScript:

$(document).ready(function() {
    $("#contactForm").submit(submitSearch);
}); 

function submitSearch(event) {
     event.preventDefault();

     //do other stuff
     alert($("#inputbox").val());
}
metadept
  • 7,581
  • 2
  • 17
  • 24