1

I've got the following output in my HTML

<input type="hidden" value="28" name="variation_id">

This value is generated dynamically. I want to write an If else statement that is dependant on this value i.e. the "28". I'm not quite sure on how to target this value since it has no ID. Is there a code to read out this value, via the "name" attribute?

I want to write the if else statement in Javascript.

1
  • Just as a side not, the number in the value attribute is actually a string. Depending on how you use this, you may need to run parseInt([value]); (replacing [value] with the value) in order to get a number you can use. Commented May 17, 2013 at 12:36

3 Answers 3

3

Assuming you only have the one element with that name:

var elem = document.getElementsByName('variation_id')[0];

if (elem.value == '28') {
    // it has that value, do something
}
else {
    // it doesn't have that value, do something else.
}

Or, in more up to date browsers:

var elem = document.querySelector('input[name="variation_id"]');

if (elem.value == '28') {
    // it has that value, do something
}
else {
    // it doesn't have that value, do something else.
}

References:

Sign up to request clarification or add additional context in comments.

Comments

1

just like this one

 var val = document.getElementsByName('variation_id')[0].value;

Comments

0

What you need is:

var value = document.getElementsByName("variation_id")[0].value;

Comments

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.