简体   繁体   中英

Search button click on keypress of enter using javascript

I have textboxes and each textbox contains search button beside that. On Key press i need to validate for alphanumeric characters and if Enter Key is pressed i need to Search. Right Now, My Textbox contains:

<asp:TextBox ID="txtId" runat="server"  TabIndex="1" MaxLength="30" onkeypress="return validateAlphaNumeric(event, this);"></asp:TextBox>
Search Button:
<asp:ImageButton ID="imgSearch" runat="server" ImgUrl=".gif" OnClientClick="returnpassTxtboxValue(imgSearch);"/>

Now if i do:

If (event.KeyCode == 13) then SearchButton.Click();

This executes the returnpassTxtboxValue(imgSearch) function of Search button and then return back to textBox function validateAlphaNumeric() of Textbox . So my test fails by throwing parameterCount exception.

Javascript for textbox:

 function validateAlphaNumeric(evt, textBox) {
        var charCode;
        charCode = (evt.which) ? evt.which : window.event.keyCode;

        if (charCode >= 97 && charCode <= 122 || charCode >= 65 && charCode <= 90 || charCode == 8 || charCode >= 48 && charCode <= 57 || charCode == 45 || charCode == 13) {
            //if (charCode == 13) {
            //    document.getElementById('SearchButton').click();

            //}
            return true;
        }
        else {
            return false;
        }
    }

Can u pls suggest me how to over come this?

Thanks,

You should do this way of implementation

    <asp:TextBox ID="txtId" runat="server"  TabIndex="1" MaxLength="30" onkeypress="return validateAlphaNumeric(event, this);"></asp:TextBox>
    Search Button:
    <asp:ImageButton ID="imgSearch" runat="server" ImgUrl=".gif" onclientClick="Validate(this);"/>


$(document).ready(function(e){
  $("#txtId").on("keyup",function(e){

     if(e.keycode == 13){ 
        $("#imgSearch").trigger("click");
     }
  }  
});

function Validate(e){
 e.preventDefault();
 // Do your validation Code here.
}

Thanks

you have to write below code on your textbox (txtId) keypress event

 if (e.keyCode == 13) $j("#imgSearch").trigger('click');

this code execute button (imgSearch) click event on press enter key

function validateAlphaNumeric(event, obj)
{
   if (event.keyCode == 13) $j("#imgSearch").trigger('click');
}

Try this

$("#txtId").keypress(function (e) {
    if (e.keyCode == 13) {
    $('#btnId').trigger('click');
    }
});

Search Button:

Please do in following way for a single textbox

$(document).ready(function(){

$("#txtId").keypress(function(e){

if(e.which==10 || e.which==13)
{
$("#imgSearch").click();
}

});

});

Need to add Return false.

if(event.KeyCode == 13){
document.getElementById('SearchButton').click();
return false;
}

It will work...thanks all :)

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