Mike
Mike

Reputation: 6934

How to trigger the right submit button after ENTER, if there are more in a HTML form?

I have a form with 2 submit buttons, but I want only the second one to be triggered, if I click enter. Unfortunately, the first one is being clicked, what should I do? Is there maybe an attribute to set the main button?

Thanks.

Upvotes: 1

Views: 972

Answers (5)

Slawomir
Slawomir

Reputation: 3343

Make one button of "submit" type. Hitting Enter should trigger submission regardless of button's relative position to the "reset" button:

<button type="reset">Cancel</button>
<button type="submit">Sign Up</button>

Upvotes: 0

Cygnusx1
Cygnusx1

Reputation: 5409

I would put the primary button with the type=submit and the other would be managed by javascript (JQuery recommended).

This way when you press enter, since there is only one type=submit button, this one will be used.

Upvotes: 1

Dr TJ
Dr TJ

Reputation: 3356

I'm not sure about HTML tags... But you can write this JS:

<script type="text/javascript">
  window.onload = function () {
    document.getElementById('button2').focus(); 
  }  
</script>

Usually, I prefer to use JQuery and AJAX like so:

$(".TextBoxesClassORAnyOtherSelector").keydown(function () {
    if (True) {
        $.ajax({
            type: "Post",
            url: "/relativeAddress/Page.aspx",
            data: { Field1: value1 },
            success: function (data, status) { // on succeed codes  },
            error: function (req, status, error) { alert(error); }
        });
    }
});

Upvotes: 1

Arne Kr&#246;ger
Arne Kr&#246;ger

Reputation: 91

This is not possible via HTML. You have to use JavaScript instead.

Example (using jQuery):

<script type="text/javascript">
    $(document).ready(function(){
        $('#FormId input:text').keydown(function(event){
            if ((event.which && event.which != 13) || (event.keyCode && event.keyCode != 13)) {
                return true;
            }

            if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) {
                $(this).parents('form').find('#SubmitButtonId').click();
                return false;
            } else {
                return true;
            }
        });
    });
</script>

Upvotes: 1

tskuzzy
tskuzzy

Reputation: 36446

Change the order of the two buttons in the HTML. Then reposition them the way you want using CSS.

To reverse the order of the buttons, you can do:

.buttons input { float: right; }

with the HTML:

<p class="buttons">
    <input type="submit" name="second" value="second">
    <input type="submit" name="first" value="first">
</p>

Upvotes: 1

Related Questions