Reputation: 153
I am new to JQuery. I have the following HTML rendered:
<span class="activate"><label id="lblMTPrinterID1">MT1</label></span>
<span class="activate"><label id="lblNTPrinterID1">NT1</label></span>
<span class="activate"><label id="lblActive1">Y</label></span>
I trying to inspect the values given by the 3 labels:
$(function (){
var tr = $(this).parents('tr:first');
var MTPrinterID = tr.find("#lblMTPrinterID1").val();
var NTPrinterID = tr.find("#lblNTPrinterID1").val();
var Active = tr.find("#lblActive1").val();
});
These vars are all returning null even those I can see them nicely in the rendered html. I am sure I am using wrong systax due to unfamiliarity. Can some one please help :)
Upvotes: 0
Views: 95
Reputation: 670
How about:
var label = $( "#lblMTPrinterID1" ).text();
That gives you the text inside the label tag as I think that's what you're after!
Upvotes: 1
Reputation: 237975
Look at this code:
$(function (){
/* some code here */
});
What does that do? It assigns a function to be run when the DOM is ready. That's what $(function(){})
does.
Inside your handler, you are using this
. The this
keyword will actually point to the document
here. You then look for parents
of the document
. Obviously this won't do anything useful.
I think you probably want to do something like this:
$(function (){
$('td').click(function() {
var tr = $(this).parents('tr:first');
var MTPrinterID = tr.find("#lblMTPrinterID1").text();
var NTPrinterID = tr.find("#lblNTPrinterID1").text();
var Active = tr.find("#lblActive1").text();
});
});
This assigns a click
handler, so when a td
element is clicked, the function will be run. this
will now point to the td
element, so it will find a parent tr
and do the search from there.
Note also that you need to call text()
not val()
, since label
elements don't have a value
.
Upvotes: 1
Reputation: 10014
Try this:
$(function (){
var MTPrinterID = $("#lblMTPrinterID1").html();
var NTPrinterID = $("#lblNTPrinterID1").html();
var Active = $("#lblActive1").html();
});
IDs should be unique for the entire page so there is no reason to filter them to be only inside the tr
(which presumably you have in your HTML but is just not shown in the code you pasted). If they are not unique to the entire, page, use classes instead.
This is also assuming that you are doing something with these var
s after assigning them, within the same function, because they will not be available outside the function when they are defined inside the function.
Upvotes: 2