1

I don't know how to add name from my input into label attr for and same input as ID. They are in same div. Do you guys know how to do it ? Thank you.

Jquery:

$('input[type="text"]').each(function () {
  var name = $("input").attr("name");
})

HTML:

<div data-role="fieldcontain">
  <label>Name:</label>
  <input type="text" name="fname" value="" />
</div>
0

3 Answers 3

3

Just get the previous element of this input field and change its text with this.name:

$('input[type="text"]').each(function() {
    $(this).prop('id', this.name)    // set 'id' of input field
           .prev('label')            // get previous sibling element
           .attr('for', this.name);  // set 'for' attribute
});
Sign up to request clarification or add additional context in comments.

3 Comments

Hi, thx for post. I don't want to change text i want put that text from attribute name to previous label attribute "for" and into same input as "id".
@user3342042 Then you should have mentioned about that in the question. Anyway it is also very easy: check the updated answer.
Thank you very much. Yes i forgot about it
0

Use $(this)

$('input[type="text"]').each(function () {
    var name = $(this).attr('name');
    $(this).prev('label').text(name);
})

Comments

0

Use .prop() instead of .attr() Since, attr() gives you the value of element as it was defines in the html on page load. It is always recommended to use prop() to get values of elements which is modified via javascript/jquery , as it gives you the original value of an element's current state dom element

$('input[type="text"]').each(function () {

     var name = $("input").prop("name");
     $(this).prev('label').text(name);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.