Reputation: 7
I used a for
loop to copy the content of the table n times. Unfortunately, the code I mentioned below works only for the 1st table only.
How can I make it work for every tables? Please suggest some solutions for this. (I am a beginner)
function copy() {
var text1 = document.getElementById("Name1").value;
document.getElementById("Name2").value = text1;
var text2 = document.getElementById("Name3").value;
document.getElementById("Name4").value = text2;
}
<tr><td rowspan="3" style="height:100px;">
Name <input type="text" name="Emp name" placeholder="enter your name" id="Name1"/><br>
ID <input type="id" name="Emp Id" placeholder="enter id" id="Name3" > </td>
<td style="height:150px;">
<input type="button" value="Get data" onclick="copy();"/>
<label for="text"> Name : <input type="text" id="Name2"></label>
<label for="text"> ID : <input type="id" id="Name4"></label>
</td></tr>
Upvotes: 0
Views: 93
Reputation: 12085
1st : Because id attribute
should be unique for each element . you should not make duplicate it . you should use class name
instead of id .
As per your comment i give some example in jquery .
$(document).on('click','.get_data',function(){
name1_val = $(this).closest('tr').find('.Name1').val();
name3_val = $(this).closest('tr').find('.Name3').val();
$(this).closest('tr').find('.Name2').val(name1_val);
$(this).closest('tr').find('.Name4').val(name3_val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1px">
<tbody>
<tr>
<td rowspan="3" style="height:100px;">
Name <input type="text" name="Emp name" placeholder="enter your name" class="Name1"/><br>
ID <input type="id" name="Emp Id" placeholder="enter id" class="Name3" > </td><br>
<td style="height:150px;">
<input type="button" value="Get data" class="get_data" /><br>
<label for="text"> Name : <input type="text" class="Name2"></label><br>
<label for="text"> ID : <input type="id" class="Name4"></label>
</td></tr> <br>
<tr>
<td rowspan="3" style="height:100px;">
Name <input type="text" name="Emp name" placeholder="enter your name" class="Name1"/><br>
ID <input type="id" name="Emp Id" placeholder="enter id" class="Name3" > </td>
<td style="height:150px;">
<input type="button" value="Get data" class="get_data" /><br>
<label for="text"> Name : <input type="text" class="Name2"></label><br>
<label for="text"> ID : <input type="id" class="Name4"></label>
</td></tr>
</tbody>
Upvotes: 1