Bounce
Bounce

Reputation: 2105

Getting input hidden value from string

I have following code (live: http://jsfiddle.net/xyZY8/1/):

var str = '<div>hello</div><ul><li>Some text...</li>' + 
          '<li>second item</li></ul>' +
          '<input type="hidden" name="some_int" value="15" />';

var myVal = $(str).find("input[name=some_int]").val();

alert(myVal);

I want to get input hidden value. But this code does not work.

Any ideas ?

Upvotes: 1

Views: 1823

Answers (1)

Rob W
Rob W

Reputation: 349232

When you create new HTML using $('<html string here>'), a new jQuery object will be created, containing all elements:

div     When you use `.find()`, the childs of the first element, <div> in this
ul        case, are checked.
    li
    li
input

Use filter() if you want to select one of these childs.

var myVal = $(str).filter("input[name=some_int]").val();

You can also wrap the HTML in a container, so that find() can be used:

var myVal = $("<div>").append(str).find("input[name=some_int]").val();

Upvotes: 3

Related Questions