Skip to content Skip to sidebar Skip to footer

Is There A Way To Set Up A Fallback For The Formaction Attribute In Html5?

I have a form that is supposed to dynamically change where it is submitted to. I am doing this by bringing in a submit button using ajax that has the formAction attribute set to wh

Solution 1:

You could bind to the submit button with jQuery, extract the formAction and apply it to the action of the form element:

Given the following HTML

<form action="defaultAction.php"id="myForm">
     <input type="submit" value="save"id="save" formAction="http://example.com/save" />
     <input type="submit" value="delete"id="delete" formAction="http://example.com/delete" />
</form>

You'd attach a delegate to the form to listen for click of submit buttons within your form:

var myForm = $('#myForm');
myForm.on('click', 'input[type=submit]', function (e) {
    var attr = this.getAttribute('formAction');

    if (attr) {
        myForm[0].action = attr; //Set the form's action to formAction//this.form.action = attr; //As per Greg's comment, this is an equivalent statement to above, and should be used if myForm reference doesn't need to be used elsewhere in your script.
    }
});

Since the click is applied as a delegate, any new submit buttons dynamically added to the form would also trigger this click function. (exception if you bind a click handler directly to the button with e.stopPropagation() in it)

Now, when the form submits, it will use the value of formAction as its action.

This jsfiddle shows the value of formAction being retrieved in the click handler.

Edit Actually, it does "click" the default submit button, even if, for example, you press Enter in a focused text field.

Solution 2:

formaction is an HTML5 attribute. This is how you use it

<form action="/url" >
     <input type="submit" value="save1"id="save1" formAction="http://example.com/save1" />
     <input type="submit" value="save2"id="save2" formAction="http://example.com/save2" />
</form>

Here is a fallback what you need.

if (!('formAction'indocument.createElement('input'))){
 $('form').on('click', 'input[type=submit]', function (e) {
    var attr = this.getAttribute('formAction');

    if (attr) {
        this.action = attr; //Set the form's action to formAction
    }
  });
}

Post a Comment for "Is There A Way To Set Up A Fallback For The Formaction Attribute In Html5?"