Reputation: 3442
I have some problems identifying an asp.net control in javascript. Here's a simple variant of my code, maybe you can see an error.
This function creates a set of button + label, it can be called multiple times:
private void AddRow(Panel pnl)
{
var myButton = new Button();
myButton.Text = "+";
myButton.Attributes.Add("onclick", "return MyJavascript();");
myButton.Attributes.Add("somevariable", "FOOBAR!");
var lblAnzahl = new Label();
pnl.Controls.Add(myButton);
pnl.Controls.Add(lblAnzahl);
}
This is the JS function the button calls:
function MyJavascript(e) {
var sender = event.target || event.srcElement;
var somevar = sender.getAttribute("somevariable");
alert('somevar: ' + somevar);
alert('ID: ' + sender.id);
}
The output is:
somevar: FOOBAR!
ID:
So I guess I get the correct sender, but for some reason the ID is always empty. The easiest way for me would be, if I could somehow set the ID of button and label myself, so that I can give it an unique ID every time AddRow() gets called, so I can easily identify the button and of course the label that belongs to the button.
What am I doing wrong?
Upvotes: 0
Views: 132
Reputation: 6764
You're not setting an ID in your AddRow function.
Change your function to this:
private void AddRow(Panel pnl, int index)
{
var myButton = new Button();
myButton.ID = "button_" + index; // add this line (the index will guarantee a distinct ID)
myButton.Text = "+";
myButton.Attributes.Add("onclick", "return MyJavascript();");
myButton.Attributes.Add("somevariable", "FOOBAR!");
var lblAnzahl = new Label();
pnl.Controls.Add(myButton);
pnl.Controls.Add(lblAnzahl);
}
You can invoke the code like this:
AddRow(pnl, 0);
AddRow(pnl, 1);
AddRow(pnl, 2);
Upvotes: 1
Reputation: 1726
You can use myButton.ClientID
or add name attribute myButton.Attributes.Add("name", "FOOBAR");
with check to be sure that name is unique and retrieve in Javascript by getElementByName
Upvotes: 2