Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to set up a fallback for the <input> 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 where I want the form to submit to (I'm bringing in a number of other things as well that are dependent on the user input, but as far as I can tell have no bearing on this question). Here's an example of my submit button:

<input type="submit" value="Edit" name="save" id="save" formAction="http://example.com" />

The URL in formAction is dynamically generated based on user input in the initial form.

Everything is working as I expected in both chrome and firefox, but despite the fact that IE 11 supposedly has support for formAction, it appears to be ignoring it. Regardless, I'd like to have the same functionality work with IE 9, which I know doesn't support formAction, so I'm trying to create a fallback.

I've used Modernizr in the past, but looking at the documentation indicates to me that it does not check for the formAction attribute. Is there a way to use the html 5 functionality of formAction while having a fallback option? I like to try to code to html 5 standards whenever possible.

like image 488
Chris Avatar asked Mar 21 '23 03:03

Chris


1 Answers

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.

like image 114
crush Avatar answered Apr 25 '23 06:04

crush