Reputation: 11
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
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'));
});
Upvotes: 2
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
Reputation: 15112
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