A Bogus
A Bogus

Reputation: 3930

Handling classes on Multiple forms with jQuery or JavaScript

I have a site with mutliple forms, and I would like to, for a specific form, loop through and manipulate the classes on divs and inputs. I can get the form id with -

var thisForm = $(el).closest('form');
var myId = thisForm[0].id

But then I am not sure how to loop through specific classes.


Example:

for each input with "class1" I want to change it to "class2"

and

for each div with "class3" I want to add "class4"


Any help would be greatly appreciated.

Upvotes: 2

Views: 94

Answers (1)

CaffGeek
CaffGeek

Reputation: 22064

Should be as simple as this

var thisForm = $(el).closest('form');
$('input.class1', thisForm).removeClass('class1').addClass('class2');
$('div.class3', thisForm).addClass('class4');

See this example http://jsfiddle.net/dXrN8/2

It's jQuery, so you don't need to loop to do these things, actions happen on everything your selector matches.

What we are doing is finding the form, and assigning it to thisForm.

Then use that to scope our selectors in the next two lines.

Then select all input.class1 elements and remove class1 and add class2.

Then select all our div.class3 elements and add class4.

Upvotes: 2

Related Questions