Kim
Kim

Reputation: 1156

How to get label of the input field?

I'm trying to get the "label" of the current input-field.

Here is the input-field in the form:

<label class='checkbox' for='AddtxtName'><input type='checkbox' data-type='UserDetails' name='txtName' id='AddtxtName'> Name</label> 

And here is the Jquery:

$('input[data-type="UserDetails"]').each(function(index, input){
    var label = $("label[for='" + input + "']");
    var name = $(input).attr('name');
    var value = $(input).is(":checked");
    if($(input).is(":checked")){
        $("#showForm").append('<div class="control-group"><label>'+label+'</label><div class="controls"><input type="text" class="input-fluid" name="' + name + '" /></div></div>');
    }
    });

How is this done correctly?

Thanks!

Upvotes: 0

Views: 1114

Answers (2)

Kim
Kim

Reputation: 1156

I figured it out!

Thanks for all the fast answers :)

Here is my solution:

var label = $("label[for='"+name+"']").text()

Upvotes: 0

mplungjan
mplungjan

Reputation: 177691

Since you know the ID you can do this in case the label is not the parent

$('input[data-type="UserDetails"]').each(function(){
  var label = $("label[for='" + this.id + "']");

If it is

   var label = $(this).parent()

Upvotes: 1

Related Questions