Pravesh S Pravesh S - 15 days ago 7
ASP.NET (C#) Question

Copy One TextBox value to another TextBox in ASP.NET in Multiple Rows

I have almost 10 rows in which I want to copy one TextBox value to another. If I assign specific ID to 1st TextBox then I can copy that value to another TextBox - I am looking to do some generalized function which can copy TextBox value to another TextBox for each row in ASP.NET.

This is my HTML for Table -`

<tr>
<td><asp:TextBox runat="server" Text=""></asp:TextBox></td>
<td></td>
<td></td>
<td><b>206a/506a</b></td>
<td>
<asp:TextBox ID="TextBox1" ClientIDMode="Static" runat="server" Text="$0.00" BackColor="Yellow" onkeyup="javascript:Copy()" />
</td>
<td>
<asp:TextBox ID="TextBox2" runat="server" Text="$0.00" ClientIDMode="Static" BackColor="Yellow"></asp:TextBox>
</td>
</tr>


I have same kind of 10 rows in which I want to use belowed JavaScript function:

<script type="text/javascript">

$('#TextBox1').keypress(function (event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) &&
((event.which < 48 || event.which > 57) &&
(event.which != 0 && event.which != 8))) {
event.preventDefault();
}
var text = $(this).val();
if ((text.indexOf('.') != -1) &&
(text.substring(text.indexOf('.')).length > 2) &&
(event.which != 0 && event.which != 8)) {
event.preventDefault();
}
});

function Copy() {
//forceNumber(("#TextBox1"));
var val1 = jQuery("#TextBox1").val();
jQuery("#TextBox2").val(val1);
}

</script>



On Keypress event, function is restricting the user to enter only two numbers after decimals.

Answer

You can achieve the desired like below.

1: Give classes to you TextBox1 and Textbox2 as from and to.

2: Onkeyup function find out the current parent tr

3: find the from and to text box in the parent tr and update values

The below snippet is with the final html generated.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="text" Text="" class="from" onkeyup="copy(event)"/></td>
<td></td>
<td></td>
<td><b>206a/506a</b></td>
<td>  
 <input type="text" Text="" class="to"   /></td>
</tr>`
  
<tr>
<td><input type="text" Text="" class="from" onkeyup="copy(event)"/></td>
<td></td>
<td></td>
<td><b>206a/506a</b></td>
<td>  
 <input type="text" Text="" class="to"   /></td>
</tr>`
  
</table>
<script type="text/javascript"t>
  
  function copy(event)
  {
          var parentRow = $(event.target).parents('tr');
          var fromVal = parentRow.children('td').find('.from').val();
          parentRow.children('td').find('.to').val(fromVal);

  };

</script>