简体   繁体   中英

Disabling enter key for selected submit buttons within a form

i have a page that contains several submit buttons however i only want one of them to be activated by the enter key

 echo "<form method=\"post\" action=\"fish.php\">\n";

 echo "<tr><td>North Pot</td><td><input type=\"text\" name=\"northpot\"><input type=\"submit\" name=\"north_all\" value=\"All\"></td>\n";

 echo "<tr><td>South Pot</td><td><input type=\"text\" name=\"southpot\"><input type=\"submit\" name=\"south_all\" value=\"All\"></td>\n";

  echo "<tr><td><input type=\"submit\" name=\"submit4\" value=\"Place\"><input type=\"submit\" name=\"clear\" value=\"Clear\"></td>\n";
 echo "<td colspan=\"2\" align=\"center\"></td></tr>\n";

 echo "</form>"; 

The button i want to be actived by the return key is submit4

i can disable the enter key for all the submit buttons but i'm struggling to do this selectively

You can capture and cancel the enter keypress on those fields like this:

$('.noEnterSubmit').keypress(function(e){
    if ( e.which == 13 ) return false;
    //or...
    if ( e.which == 13 ) e.preventDefault();
 }); 

Then on your inputs with type as submit just give them a class="noEnterSubmit" :)

In jQuery 1.4.3 you can shorten it to this:

$('.noEnterSubmit').bind('keypress', false);

This is not possible in plain HTML. How ever you may do it in Javascript :

function keyPressed(e)
{
     var key;      
     if(window.event)
          key = window.event.keyCode; //IE
     else
          key = e.which; //firefox      

     return (key != 13);
}

And then in your page, either add

<body onKeyPress="return keyPressed(event)">

if you want to disable enter on the hole page, or

<input type=”text” onKeyPress=”return keyPressed(event)”>

if you only want to disable it on a single form (You must then add this to all your inputs).

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