Joe Yan
Joe Yan

Reputation: 2095

How to capture enter key in html and redirect to asp page?

in my plain HTML page, i had a textbox for user to input keyword and then redirect to asp page. i use javascript to capture keywords when user click submit button.

but when user press enter, the HTML page will reload and return error page. how can i capture enter key event ? so that it will redirect to asp page. thanks

my javascript code as follows:

function searching() {            
            var keywordsStr = document.getElementById('keywords').value;
            var cmd = "http://xxx/SearchEngine/Searching.aspx?keywords=" + encodeURI(keywordsStr) ;
            window.open(cmd);
        }

my html code as follow:

   <form name="form1" method="post" action="" >
     <input name="keywords" type="text" id="keywords" size="50" >
     <input type="submit" name="btn_search" id="btn_search" value="Search" onClick="javascript:searching(); return false;">
     <input type="reset" name="btn_reset" id="btn_reset" value="Reset">
   </form>

Upvotes: 1

Views: 2698

Answers (3)

Luca Borrione
Luca Borrione

Reputation: 17022

why don't you just open your form's result in a new window?
I prefer to use post:

<form action="http://xxx/SearchEngine/Searching.aspx" method="post" target="_blank">

but you can use a get call, as you did in your snippet

<form action="http://xxx/SearchEngine/Searching.aspx" method="get" target="_blank">



If you really want to detect the enter key .. in your case I would suggest you to use onkeydown event to the whole page to prevent to fire events associated with the enter key (eg submit your form), by using:

document.onkeydown = checkKeycode
function checkKeycode(e) 
{
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if (e) keycode = e.which;
    // alert("keycode: " + keycode);
    if (keycode == 13)
    {
        alert('enter key is pressed: now do something');
    }
}

Upvotes: 0

Reinder Wit
Reinder Wit

Reputation: 6615

your 'action' attribute is empty, which means the HTML page will post to itself (reloading basically). You need to put the URL of your ASP page in there to be able to post the data.

 <form name="form1" method="get" action="http://xxx/SearchEngine/Searching.aspx">
     <input name="keywords" type="text" size="50" >
     <input type="submit" name="btn_search" value="Search">
     <input type="reset" name="btn_reset" value="Reset">
 </form>

and you might want to change the method to method="get" to mimic your javascript function. If you want the submit to create a new window, you can add a target attribute to the form:

target="_blank"

Upvotes: 0

painotpi
painotpi

Reputation: 6996

If you're open to using jquery,

You can do something like,

$("#keywords").keyup(function(e){
   if(e.keyCode == '13')
   {
       //enter key
   }
});

Upvotes: 2

Related Questions