May
May

Reputation: 165

Is there a way I can make a button as default on a form?

Here's my code:

<FORM ACTION="../cgi-bin/cgi4.pl">
Go to check-out page? 
<INPUT TYPE=SUBMIT NAME="checkout" VALUE="Yes"> 
<INPUT TYPE=SUBMIT NAME="checkout" VALUE="No"> 
</FORM>

I would like the Yes to be default when I click enter. Is this possible?

Upvotes: 2

Views: 131

Answers (3)

Hasan Fahim
Hasan Fahim

Reputation: 3885

Try this:

<FORM ACTION="../cgi-bin/cgi4.pl">
    Go to check-out page? 
    <INPUT TYPE=SUBMIT id='btnYes' NAME="checkout" VALUE="Yes" onclick="doSomething(); /> 
    <INPUT TYPE=SUBMIT NAME="checkout" VALUE="No" onkeydown="if (event.keyCode == 13) document.getElementById('btnYes').click()" />         
</FORM>

Please note: You need to add onkeydown on each control that you need to capture enter key on.

Upvotes: 0

Rohan Verma
Rohan Verma

Reputation: 445

I would suggest that you use tab index property.

<FORM>
    <input type ="text" tabindex="3"/>
    <INPUT TYPE="SUBMIT" NAME="checkout" VALUE="Yes" tabindex="1" /> 
    <INPUT TYPE="SUBMIT" NAME="checkout" VALUE="No" tabindex="2" /> 
</FORM>

I would not use javascript as if a person does not want to submit and he presses 'enter' he would be forced to do that. Maybe he uses the search bar on the top of your webpage and presses enter, but both forms will be submitted.

http://jsfiddle.net/EUUcG/3/


But if that is not the case, you can use the javascript function:-

function searchKeyPress(e) {
    // look for window.event in case event isn't passed in
    if (window.event) {
        e = window.event;
    }
    if (e.keyCode == 13) {
        document.forms["myform"].submit();
    }
}

This one is better:

<script>
    window.onload=function() {
      document.getElementsByName("checkout")[0].focus();
    } 
</script>

by @mplungjan

Upvotes: 1

mplungjan
mplungjan

Reputation: 178285

You could do this:

<script>
window.onload=function() {
  document.getElementsByName("checkout")[0].focus();
}
</script>
<FORM ACTION="../cgi-bin/cgi4.pl">
Go to check-out page? 
<INPUT TYPE=SUBMIT NAME="checkout" VALUE="Yes"> 
<INPUT TYPE=SUBMIT NAME="checkout" VALUE="No"> 
</FORM>

In HTML5 add autofocus to the button

<input type="submt" name="checkout" value="Yes" autofocus>

http://jsfiddle.net/mplungjan/mM9VJ/

Upvotes: 1

Related Questions