Samantha J T Star
Samantha J T Star

Reputation: 32818

How can I change the type of a button from "button" to "submit" with jQuery?

I have the following form:

<form id="xx">
<button type="button">Submit</button>
<button type="button">Submit and Close</button>
<button type="button">Close</button>
</form>

How can I change the type of my buttons that contain the word "Submit" from a type "button" to a type "submit"?

Upvotes: 3

Views: 166

Answers (4)

billyonecan
billyonecan

Reputation: 20260

Something like this should work (untested):

$('button').each(function() {
    if($(this).text().match(/submit/i)) {
        $(this).prop('type', 'submit');
    }
});

edit

It's worth pointing out that this, and all of the other answers here will not work in Internet Explorer:

Note: jQuery prohibits changing the type attribute on an or element and will throw an error in all browsers. This is because the type attribute cannot be changed in Internet Explorer.

http://api.jquery.com/attr/

(I've tested this with .prop() as well, and although no error is thrown, it doesn't work)

Upvotes: 0

Marius
Marius

Reputation: 1073

I your button had an id e.g. "button" this could be acieved in the following way:

$('#button').prop('type', 'submit');

If you wish to change the attribute of all the buttons with the text "Submit", this could be achieved in the following way:

$('button').each(function(){
    if($(this).text().indexOf("Submit") != -1){
        $(this).prop('type','submit');
    }
});

Upvotes: 3

NullPoiиteя
NullPoiиteя

Reputation: 57322

create the id in the button and do the following thing

$('#buttonid').replaceWith($('#buttonid').clone().attr('type', 'submit'));

Upvotes: 1

Andy
Andy

Reputation: 30135

$('button').filter(function(){
    return $(this).text().toLowerCase().indexOf('submit') != -1;
}).prop('type','submit');

first filter for buttons which have "submit" as text, then change the property.

Upvotes: 3

Related Questions