Reputation: 67283
I have a simple ASPX page based of a master page. On the ASPX page, I have two drop downs and a button. When pressing the button, I want to execute some javascript. To do this, I have used the Button's attribute collection (Add("onclick", script)).
My script looks like this:
string script = "return confirm ('You have selected' + document.getelementbyid(DropDownList1).value + document.getelementbyid(DropDownList2).value)");
Button1.Attributes.Add("onclick", script);
The drop down box element names are spot on, but why doesn't the javascript fire? The button's click event (obviously) gets fired when I click the event, but nothing happens.
This is being done in C#. If I use ASPX and write a basic javascript function in the ASPX markup, intellisense doesn't even come up with a value property for documentgetelementbyid. Why? My browser is fully js enabled (Firefox) as I had this working before but when I added the masterpage and based my ASPX page of that, everything went pear shaped.
Why doesn't the above script works?
Thanks
Upvotes: 0
Views: 810
Reputation: 4169
had you try adding the client ID
string script = "javascript:return confirm ('You have selected' + document.getelementbyid('"+DropDownList1.ClientID+"').value + document.getElementByid('"+DropDownList2.ClienID+"').value)");
Upvotes: 5
Reputation: 38882
When some JavaScript code seems to not work, it's probably because the syntax is invalid.
To prevent that you can:
If not, try playing with the OnClientClick property of the button.
Upvotes: 1
Reputation: 871
I'm not entirely sure of your environment but you may want to take a peek at the source that's being generated by your ASP page. Master pages add a prefix to control names "breaking" the getElementById call. Take a look at the following: http://west-wind.com/weblog/posts/4605.aspx to see if that corrects your problem.
Upvotes: 2
Reputation: 4943
You also should have the "javascript" in your attributes:
string script = "javascript:confirm ('You have selected' + document.getElementById(DropDownList1).value + document.getElementById(DropDownList2).value)");
Button1.Attributes.Add("onclick", script);
Upvotes: 0