I have a textbox and labels inside rows of a table. To access the textbox I’m using
data= $(this).find('#txtName').val();
Now I’m not able to access the label in the same way. The label is rendered as
<label for="Total">$65.00</label>
How can I access the label’s value and assign a value to it?
It’s hard to say when you haven’t shown your HTML structure, but a couple of possibilities:
1) The label is separate
If your label is separate, like this:
…then given the
idof the textbox istxtName, you can use an attribute selector to search for the label with thatforattribute:Edit: So if the name of the field is
Total, it would be:To set its contents (not “value”), use either
textorhtml:2) The textbox is within the label:
Edit: Now that Drackir has fixed the formatting of your post, we can see that you’re using the
forattribute as above. Keeping this second part in case someone else sees this and is doing it this way.If the textbox is within the label, like this:
…then if
$(this).find('#txtName').val();works, this should work:(If the textbox really is an immediate child of the label, you could use
.parent()instead of.parents('label'), but the latter is useful if the text box is a descendant rather than an immediate child.)Once you have the
label, you can’t just set its content viatextorhtmlbecause you’ll wipe out the field (since it’s inside the label). You could do this:That temporarily removes the text box for safekeeping (
detachleaves event handlers in place), sets the text of the label to “Field name: “, and then appends the textbox back to it.More:
SelectorstexthtmlparentsparentdetachappendTo