saurabh sharma
saurabh sharma

Reputation: 23

how to pass asp.net C# control ID in Javascript function multiple parameter

My objective is that whenever I insert in textbox1 , it will automatically updated in TextBox2. I don't want to use "input tag" or postback. Kindly correct below code only :)

<script type="text/javascript">
        function OneTextToother1(a, b) {
            alert(a.value); //it render correct value
            alert(b.value); // it is undefined
            document.getElementById(b).value = document.getElementById(a).value
         }
    </script>


<asp:TextBox ID="txtFirst" runat="server" onkeyup="OneTextToother1( this, ' <%= txtSecond.ClientID %>');" ></asp:TextBox>    
<asp:TextBox ID="txtSecond" runat="server"></asp:TextBox>

As suggested by John Answer. I'm able to achieve what he suggested. Kindly modify above code only. I want to have generic JS function and in asp textbox declaration, I'll pass source and destination clientID. Is it achievable ?

Upvotes: 1

Views: 1529

Answers (1)

user7138697
user7138697

Reputation:

Change onkeyup to:

onkeyup="OneTextToother1();"

Then the JavaScript can just be:

function OneTextToother1() {
            document.getElementById('<%= txtSecond.ClientID %>').value = document.getElementById('<%= txtFirst.ClientID %>').value;
        }

Hope it helps

EDIT:

Change onkeyup to:

onkeyup="OneTextToother1(this, 'txt_delivery');" 

Where txt_delivery is the id of the control you want to change

We then need to amend the javascript.

The OneTextToother will look like:

 function OneTextToother1(a, b) {
            document.getElementById(findItemInArray(b)).value = a.value;
        }

we need to add an additional function:

function findItemInArray(b) {
            var items = [
                ['txt_delivery', '<%= txt_deliverydate.ClientID %>'],
                ['txt_route', '<%= txt_route.ClientID %>']
            ];
            for (var k = 0; k < items.length; k++) {
                if (items[k][0] === b ) {
                    return items[k][1];
                }
            }
        }

Since we cannot pass ClientIDs to the javascript function its best to store each ASP Control in a javascript array.

var items holds the name of the ASP control then a method of obtaining theclient id. We then loop through the array to find the parameter passed in. I do not believe there is a simpler solution for a generic way of doing it to support multiple controls.

You just need to add each of the c# controls to the javascript function and then pass through the control name.

If this answers your question, Id appreciate marking as correct.

Upvotes: 1

Related Questions