Scarlet Aarens
Scarlet Aarens

Reputation: 59

Allow button click function on the Enter Key in Textbox

In MVC .NET, I have one textbox to allow search associated with one button of type "button" (I can not make it submit due to functionality) which when clicked calls one method that allows to search.

When the user enters search number in textbox and hits 'Enter' key on keyboard I want search to be called.

I do not have any submit button in my @Html.BeginForm()

Following is the code

@Html.TextBoxFor(m=>m.SearchNo,new {@class="form-control",@maxlength="12" });

<input type="button" id="btnSearch" value="Search" onclick="search();"/>

I have tried using following but it does not work:

$("#SearchNo").keyup(function(event){
    if(event.keyCode == 13){
        $("#btnSearch").click();
    }
});

Please help me with this

Upvotes: 1

Views: 3164

Answers (1)

Divyang Desai
Divyang Desai

Reputation: 7864

You're trying with keyup, but the keyup event is sent to an element when the user releases a key on the keyboard.

You could use keypress, where the keypress event is sent to an element when the browser registers keyboard input.

$("#SearchNo").keypress(function(event){
  if(event.keyCode == 13){
       alert('You pressed enter!');
    $("#btnSearch").click();
  }
});
$("#btnSearch").click(function() { alert("click"); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="SearchNo">

<input type="button" id="btnSearch" value="Search" />

Update:

In that case, you can call your function search() in this way:

$("#SearchNo").keypress(function(event) {
  if (event.keyCode == 13) {
    alert('You pressed enter!');
    Search();
  }
});

function Search() {
  // your ajax call here.
  alert("hi");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" id="SearchNo">
<input type="button" id="btnSearch" value="Search" onclick="Search();" />

Upvotes: 1

Related Questions