I’m working on a javascript function which takes in the names of three controls, then find them on the page. There are five sets of these controls. For simplicity, I would like to use the same function and pass in the set of control names, then have the function dynamically find the controls by clientID. Is there a way to do this?
Here’s what I have so far…
function InsertKeyword(keywordCtrl, subjCtrl, bodyCtrl) {
var ctrl;
if (OnSubj) ctrl = $find("<%=" + subjCtrl + ".ClientID%>");
if (OnBody) ctrl = $find("<%=" + bodyCtrl + ".ClientID%>");
if (OnSubj == 1 || OnBody == 1) {
var selectedIndex = document.getElementById(keywordCtrl).selectedIndex;
var selectedText = document.getElementById(keywordCtrl).options[selectedIndex].text;
var strSpan = '<u>' + selectedText + '</u> ';
ctrl.pasteHtml(strSpan);
}
}
This doesn’t work, but it illustrates what I’m trying to do.
How do you dynamically find the ClientIDs of controls using javascript?
<%= %>is server-side, not client-side code, so instead of…You should have something like…
Where
subjCtrlandbodyCtrlare actual server-side control objects.The only way you could get your JavaScript to work was if you CALLED the function something like this…
And then had your JavaScript something like…
UPDATE
Based on the comment by the OP, it is not possible to use the
<%= %>syntax when declaringOnClientClickattribute on a server-side control via the mark-up.The following will not work, and the
<%=myCtrl.ClientID%>will be rendered as exactly that when sent to the browser…Instead you need to set the attribute via the code-behind (C# assumed) via one of these methods…