Pregunta

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.

¿Fue útil?

Solución 2

just like this one

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

Otros consejos

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:

What you need is:

var value = document.getElementsByName("variation_id")[0].value;
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top