简体   繁体   中英

accessing ASP.NET controls in Javascript

I have following Javascript line in my ASP.NET web app:

document.getElementById('<%=myTextBox[0].ClientID %>').value = "test";

how can I access myTextBox elements? for instance I want to change 5th element of this server side array, I want to pass a server side parameter to my function, how can I do it?

for instance:

server side:
ddl.Attributes.Add("onChange", "return OnFoodChange(this,'" + i + "');");


javascript function:
function OnFoodChange(myCmb,myIndex)

using document.getElementById('<%=myTextBox[myIndex].ClientID %>').value = "test"; gives me error, it says that myIndex is not defined, I think because myIndex is used like a server side parameter, how can I solve it?

it is my full JavaScript function:

   function OnFoodChange(myCmb,myIndex) {
               //alert('5');
try{
               var q = document.getElementById('<%= HFFoodPrice.ClientID %>').value.toString();
           var q2 = q.split(';');
           var index = 0;
           //alert(myCmb.selectedIndex.toString());

           //var e = document.getElementById(myCmb);
           var strUser = myCmb.options[myCmb.selectedIndex].value;

           document.getElementById('<%=myTextBox[0].ClientID %>').value = strUser;

           for (var j = 0; j < q2.length; j++) {
               if (q2[j] != '') {
                   var q3 = q2[j].split(',');
                   {

                   }
               }
           }
           }
           catch(err)
           {
           alert(err.message);
           }
       }

Send this control id of textbox instead of sending index as asp.net control id might not be as you expect,

In Code behind

ddl.Attributes.Add("onChange", "return OnFoodChange(this,'" + myTextBox[i].ClientID + "');");

In HTML

function OnFoodChange(myCmb,myTextBoxId) {
 currentTextBox = document.getElementById(myTextBoxId);
//Your code...
}

You are trying to Mix Server side with Client side. it does not work like this. you need to transfer your server array to javascript on server then you will be able access its index on clien side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM