Navin Rauniyar
Navin Rauniyar

Reputation: 10555

extracting id of input from label

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

Answers (4)

Roko C. Buljan
Roko C. Buljan

Reputation: 206689

$('label').text(function(){
   return $('#' + $(this).prop('for')).val();
});

http://api.jquery.com/prop/

Upvotes: 0

Ja͢ck
Ja͢ck

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

Milind Anantwar
Milind Anantwar

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 
});

Working Fiddle

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

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

Related Questions