views:

331

answers:

6

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

+1  A: 

case sensitive: document.getElementById?

MikeW
+1  A: 

Shouldn't DropDownList1 and DropDownList2 be in quotes?

jlew
+1  A: 

When some JavaScript code seems to not work, it's probably because the syntax is invalid.

To prevent that you can:

  • Validate your current statement (I'm thinking that maybe the ids of the drop-downs should be surrounded by single quotes).
  • Try with a simple alert first and see if it works -- alert('Hello world'); --

If not, try playing with the OnClientClick property of the button.

GoodEnough
A: 

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);

asp316
No, should not be needed.
erikkallen
+5  A: 

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)");
Oscar Cabrero
I think you'll need quotes round the ID as well i.e.string script = "javascript:return confirm ('You have selected' + document.getelementbyid('"+DropDownList1.ClientID+"').value + document.getelementbyid('"+DropDownList2.ClienID+"').value)");
Tim Saunders
Also I think element needs a capital E as well as the I in id i.e. getElementById
Tim Saunders
u r rigth, Thanks
Oscar Cabrero
+2  A: 

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.

toddk