Garry_G Garry_G - 4 months ago 12
jQuery Question

How to use jQuerie .find() to retrieve a value from an embedded object

The following code is embedded in a Multiview, all I want to do is access the Doc1Amount1 TextBox value, that is part of the BodyCode div, which is loaded into the DocBody div.

<asp:View ID="Tab2" runat="server">
<div class="HeaderLine">02: Documentation</div>
<br />
<asp:HiddenField ID="HiddenField1" runat="server" />
//a<asp:Label ID="Label1" runat="server" Text ="Label1"></asp:Label>b
<div id="DocBody" />
<script>
$("#DocBody").load('LabReportContent/DocumentationSub.aspx #BodyCode');
$(window).load(function () {
var current = $('#DocBody');
$("#HiddenField1").val(current.contents().find("#Doc1Amount1").val());
});

</script>
</asp:View>


The div is overwritten successfully, and all the loaded objects are showing as expected, but the find command is bringing back a blank value.

I initially wrote this without the $(window).load, and thought the contents of Doc1Amount1 weren’t showing because the page wasn’t loaded properly.
But the same thing is still happening after adding the window load to this.

Any help would be appreciated, as I'm relatively new to jQuerie.

Answer

You don' need contents(). And you should execute the code simple after the load, because window load may be to early. You can use the callback of the .load() function.

$("#DocBody").load('LabReportContent/DocumentationSub.aspx #BodyCode', function() {
    var current = $('#DocBody');
    $("#HiddenField1").val(current.find("#Doc1Amount1").val());
    $("#Label1").text(current.find("#Label1").text());
});

And you can select the child elements directly by context too, without using find.

var current = $('#DocBody');
$("#HiddenField1").val($("#Doc1Amount1", current).val());
$("#Label1").text($("#Label1", current).text());