Determine which element submitted a form from within onsubmit

后端 未结 5 763
小鲜肉
小鲜肉 2020-12-19 03:31

Is there a way to determine which element submitted a form from within an onsubmit handler? Trying to write a generic handler that knows which element was clicked. For examp

相关标签:
5条回答
  • 2020-12-19 04:01

    Click events bubble, so you could just add an "onclick" listener to the form itself, that checks if the click target source is a submit button; if so, store a reference to it somewhere associated with the form that you can access from your onsubmit handler.

    If you want to handle "Enter"-submitted forms properly too, listen to the form's "onkeypress" or "onkeydown" event, check for "Enter", and clear your submit-button info if the event target ISN'T a submit button.

    0 讨论(0)
  • 2020-12-19 04:15

    My fallback is walking the DOM to find all buttons that could cause a submit, but I'd like to avoid that.

    ...and adding click listeners to them to store the ‘last clicked’ button which is then read by the submit listener, right?

    I can't think of any other way, sorry.

    0 讨论(0)
  • 2020-12-19 04:17

    I would not use a standard submit button-type.

    Make the submit function take an extra argument which represents the element that submitted it, and the button would have an onclick that sends this as the parameter:

    <input type="button" onclick="submitHandler(this)">
    
    0 讨论(0)
  • 2020-12-19 04:18

    An alternative solution would be to move the event trigger from the form's submit event, to the submit element's onclick event, as such:

    <form name='form1'>  
        <input type="submit" name="submit1" onclick="onSubmitHandler"/>
        <input type="submit" name="submit2" onclick="onSubmitHandler"/>
    </form>
    

    In your handler function you can determine the submitting element simply by inspecting the event target's name, and if you need access to the form's information or other elements, you can get this from the submit elements "form" attribute.

    0 讨论(0)
  • 2020-12-19 04:18

    This solution works in Firefox. I haven't checked it in other compliant browsers or IE.
    I'm not too hopeful for IE, you'd have to look into it and post your results.

    <form id="myForm">
        <input type="submit">
        <input type="submit">
    </form>
    

    _

    document.getElementById('myForm').addEventListener( 'submit', function( e ){
        e.preventDefault();
        e.explicitOriginalTarget.style.background = 'red';
    }, false );
    
    0 讨论(0)
提交回复
热议问题