Mr. Mike
Mr. Mike

Reputation: 453

How to get value from input type hidden with Javascript in correct way?

I have a code

HTML :

<input type="hidden" name="test[]" id="test_0" value="123456789">

Javascript :

$(".test").each(function(){
   console.log('Test Value : '+ $(this).val());
});

Result :

Test Value =

The question :

Why result of console.log for $(this).val() inside my Javascript code give result empty ? And how to fix it without change the Javascript code?

Thank you

Upvotes: 0

Views: 153

Answers (4)

Leandro Gatti
Leandro Gatti

Reputation: 97

In the HTML, you have to add a class to input

The problem, is that you are not getting any element, because you haven't any element with that class. I think that's all.

Upvotes: 0

Obsidian Age
Obsidian Age

Reputation: 42304

The problem is that $(".test") targets the class test, not the name test. In order to solve that by only changing the HTML, simply give the input the relevant class:

<input type="hidden" name="test[]" class="test" id="test_0" value="123456789">

A working fiddle demonstrates this here.

Hope this helps :)

Upvotes: 2

Chava Geldzahler
Chava Geldzahler

Reputation: 3730

You are not targeting the desired element.

Try this:

$("#test_0").each(function(){
   console.log('Test Value : '+ $(this).val());
});

Upvotes: 0

Dev.DY
Dev.DY

Reputation: 455

test class is not defined.

try example,

console.log('Test Value : '+ $('#test_0').val());

Upvotes: 0

Related Questions