user3092412
user3092412

Reputation: 11

Set Elements value to its ID

I need to set the value of all input elements to their id with jquery. I tried the following which does not work.

<HTML>
<input id="fname" name="fname" type="text">

<script>
$('input').val($('input').attr('id'));

Upvotes: 0

Views: 151

Answers (3)

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

You should iterate through that element collection, and in each iteration you have to set the current element's id/value by its own value/id. You have to read .each() and .attr() to get more knowledge about it.

Try,

$('input').each(function(){   
 $(this).attr('id',$(this).val());
});

or if i misunderstood your title,

Try

$('input').each(function(){   
 $(this).val($(this).attr('id'));
});

DEMO

Upvotes: 2

Stoic
Stoic

Reputation: 10754

You should iterate through each input element and set their value accordingly. Moreover, I would advise to do this once, when the page has been loaded.

Script:

$(document).ready(function() {
  $('input').each(function() {
    $(this).val($(this).attr('id'));
  });
});

Upvotes: 0

Venkata Krishna
Venkata Krishna

Reputation: 15112

JSFIDDLE DEMO

You have to use .each() to loop through all input elements and set its value using this.id.

$('input').each(function(){
    $(this).val(this.id);
});

Upvotes: 0

Related Questions