Reputation: 10555
html
<label for="my_id">my label</label>
<input id="my_id" type="text" value="my value" />
now using label how to extract the id of input
$('label').text(function(){
return $('input $(this).attr('for')').val();// like input#my_id
});
I think it's not correct way. How to do?
Upvotes: 4
Views: 62
Reputation: 206689
$('label').text(function(){
return $('#' + $(this).prop('for')).val();
});
Upvotes: 0
Reputation: 173662
You can simply use the htmlFor
property of the label to reference the text box:
$('label').text(function() {
// find tag by id and return its value
return $('#' + this.htmlFor).val();
});
Having read the question again, you may be looking for just this:
$('label').text(function() {
return 'input#' + this.htmlFor;
});
See also: label
Upvotes: 4
Reputation: 82241
it should be:
$('label').text(function () {
return $('input#' + $(this).attr('for')).val(); // like input#my_id
//or
return $('#' + $(this).attr('for')).val(); // like #my_id
});
Upvotes: 1
Reputation: 67217
The way you are forming the dynamic selector inside the receiver function is completely wrong,
Try,
$('label').text(function(){
return $('#' + $(this).attr('for')).val();
});
Or if your original HTML structure is same as the structure given, then you can use .next()
,
$('label').text(function(){
return $(this).next('input').val();
});
Upvotes: 0