Break the Law
Break the Law

Reputation: 217

getting an attribute-value in a class using javascript

I don't know if this question has been asked here on SO, i just don't know the right word.

I have this input tag:

 <input type = "text" class="inputbox holdout-7"></input>

How do I get the holdout's value of 7 from the class using javascript?

This is because I wanted to add custom attributes but when the page is rendered, my custom attribute is not displayed. Some advised me to put them in a class instead.

For example:

<input type = "text" class = "inputbox" holdout="7"></input>

when the page is rendered, the holdout is not included, therefore I cannot get the value.

Upvotes: 0

Views: 44

Answers (1)

mohamedrias
mohamedrias

Reputation: 18566

var inputBox = document.querySelector(".inputbox"),
    classname = inputBox.className,
    regEx = /holdout-(\d+)/,
    holdoutValue = classname.match(regEx)[1];

It will return you 7

To set that as attribute in your input box:

inputBox.setAttribute("data-holdout",holdoutValue);

it's recommended to use data-holdout instead of holdout.

Upvotes: 2

Related Questions