Thierry Lam
Thierry Lam

Reputation: 46264

Can jQuery be used to select elements from a returned string html?

For the following jQuery code:

$("#select").change(function() {
    $("#output").load("/output/", {}, function(data) {
        // I want to extract the value of an element in data
    }); 
});

The content of data is:

<div>
  Something
</div>
<input type="hidden" name="ajax-output" value="100" />

I want to get the value ajax-output from the data output. How can I do that using jQuery?

Upvotes: 3

Views: 3934

Answers (2)

Nick Craver
Nick Craver

Reputation: 630389

To get it directly, since it's at the root, you need .filter(), like this:

$(data).filter("input[name='ajax-output']").val();

Or get it from the one you just inserted (via the .load() call itself) using .find():

$(this).find("input[name='ajax-output']").val();

Upvotes: 7

Zafer
Zafer

Reputation: 2190

Put an invisible div inside the page with the id "invisibleDiv". Then by the following code, you should be able to get the value of ajax-output:

$("#invisibleDiv").append(data);
var data = $("#invisibleDiv").find("input[name='ajax-output']").val();

Upvotes: 1

Related Questions