my label now using the labe...">

Retrieve input id from label

HTML

<label for="my_id">my label</label>
<input id="my_id" type="text" value="my value" />

now using the label how to extract input id

$('label').text(function(){
  return $('input $(this).attr('for')').val();// like input#my_id
});

I think this is not the right way. How to do it?

+4
source share
4 answers

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 script

+1
source

You can simply use the htmlForlabel property to refer to the text field:

$('label').text(function() {
   // find tag by id and return its value
   return $('#' + this.htmlFor).val();
});

After reading the question again, you can only look for this:

$('label').text(function() {
   return 'input#' + this.htmlFor;
});

See also: label

+4
source

The way you form a dynamic selector inside a receiver function is completely wrong,

Try

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

Or, if your original HTML structure is the same as the specified structure, you can use .next(),

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

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

0
source

Source: https://habr.com/ru/post/1528902/


All Articles