1

I have a number of inputs in some forms and I would like to add unique classes to each input based on the input name.

So for example this:

<input name="first_name">

... would become this using JQuery:

<input name="first_name" class="first-name">

I've searched around but could not find much reference to extracting the input name.

1 Answer 1

6

Try:

$("input").each(function() {
  $(this).addClass($(this).attr("name"));
});
Sign up to request clarification or add additional context in comments.

1 Comment

Might need to add a .replace(/_/g, '-') in there to translate the underscores to dashes, as in his example. Otherwise looks good.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.