Accessing Label inside a Row in JQuery
I 开发者_JS百科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:
<tr>
<td><label for='txtName'>Some field</label></td>
<td><input type='text' id='txtName'></td>
</tr>
...then given the id
of the textbox is txtName
, you can use an attribute selector to search for the label with that for
attribute:
var label = this.find("label[for=txtName]"); // If the label is also within `this`
// or
var label = $("label[for=txtName]"); // Find it no matter where it is
Edit: So if the name of the field is Total
, it would be:
var label = this.find("label[for=Total]"); // If the label is also within `this`
// or
var label = $("label[for=Total]"); // Find it no matter where it is
To set its contents (not "value"), use either text
or html
:
label.text("Field name");
label.html("Field <em>name</em>");
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 for
attribute 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:
<tr>
<td>
<label>Some field: <input type='text' id='txtName'></label>
</td>
</tr>
...then if $(this).find('#txtName').val();
works, this should work:
var textBox = $(this).find('#txtName');
var label = textBox.parents('label');
// Do something with `textBox.val()` and `label`
(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 via text
or html
because you'll wipe out the field (since it's inside the label). You could do this:
var textBox = $(this).find('#txtName');
var label = textBox.parents('label');
textBox.detach(); // temporarily remove from the DOM
label.text("Field name: ");
textBox.appendTo(label);
That temporarily removes the text box for safekeeping (detach
leaves event handlers in place), sets the text of the label to "Field name: ", and then appends the textbox back to it.
More:
Selectors
text
html
parents
parent
- Traversing
detach
appendTo
You can get label value by $("#yourlabelid").text()
and set its value by $("#yourlabelid").text(value)
精彩评论