Danny Englander
Danny Englander

Reputation: 2044

jQuery addClass with prepended name based on input value

I can add a class to a form element simply by doing something like this:

$("input").each(function() {
  $(this).addClass($(this).attr("name"));
});

Essentially that grabs the form value and adds it to the element as a class. Probably fine in most cases but sometimes the values will be numbers. So that leaves me with something like this:

<input type="radio" id="amount-5" name="submitted" value="50" class="form-radio 50">

I suppose then, I could target with CSS as .form-radio.50 but it probably would be better to prepend some text in front of the added value class. Ideally

<input type="radio" id="amount-5" name="submitted" value="50" class="form-radio radio-50">

I tried:

$("input").each(function() {
  $(this).addClass($('radio-class-' + this).attr("value"));
});

... and that did not work. I'm out of ideas. Here's my fiddle.

Upvotes: 1

Views: 816

Answers (1)

Alex
Alex

Reputation: 10216

That is actually pretty close, but you can simply work with strings like so:

$("input").each(function() {
  $(this).addClass('radio-class-' + $(this).attr("value"));
});

or

$("input").each(function() {
  $(this).addClass($(this).attr("type") + '-' + $(this).attr("value"));
});

So you can also differ by input type :)

Just to give a brief explanation why what you did does not work:

$(this).addClass( $('radio-class-' + this).attr("value") );

$() is a selector (in most cases), so you are basically selecting an element of type radio-class-[this] which does not exist. Also, this is the reference of the current object and i believe cannot be transformed into a string by writing 'radio-class-'+this. Hope that makes sense to you. Just select the object: $(this) turns this into a jQuery object sothat you can access jQuery functions, like .attr() which will return a value to use as string

Upvotes: 3

Related Questions