netdigger
netdigger

Reputation: 3789

Why can't I select my value in jQuery?

It's really frustrating. I've always used .val() like this, but now it doesn't work.

I'm using jQuery v1.7.2.

I have a facebox box which I initiate with a hidden value so I know what value I should change on the main page when facebox is done.

I have this HTML code:

<hidden type="hidden" value="hello" id="testid" name="testname" />

And in jQuery I've logged:

console.log($('[name="testname"]'));
console.log($('#testid'));
console.log($('#testid').val());
console.log($('[name="testname"]').val());

And this outputs:

[<hidden type=​"hidden" value=​"hello" id=​"testid" name=​"testname">​</hidden>​]
[<hidden type=​"hidden" value=​"hello" id=​"testid" name=​"testname">​</hidden>​]
(empty line)
(empty line)

So why cant I access this value?

I'm using facebox with AJAX and I know that if I use facebox with divs it will copy the dom element so that I get two with same IDs but this shouldnt happend with AJAX? And also then I would get more elements returned on the first two lines, wouldnt I? A strange thing is if I inspect the elements in Chrome I see that the input box has changed to:

<hidden type="hidden" value="hello" id="testid" name="testname"></hidden>

But maybe that doesn't matter?

Upvotes: 0

Views: 88

Answers (2)

Quentin
Quentin

Reputation: 944530

There is no <hidden> element in HTML, so jQuery doesn't have the special handling needed to support its val() method.

You want <input>. It is generally a good idea to run your HTML through an automated validator that can pick up this type of error.

(You could also use attr('value') but writing valid HTML is a much better idea)

Upvotes: 2

Christofer Eliasson
Christofer Eliasson

Reputation: 33875

There is no element hidden. Do you mean <input type="hidden">?

If you actually want to use a custom element, I believe you will have to use the .prop() method:

console.log($('#testid').prop("value"));

Upvotes: 5

Related Questions