GurdeepS
GurdeepS

Reputation: 67283

ASP.NET, Visual Studio, C# and Javascript

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

Answers (6)

Oscar Cabrero
Oscar Cabrero

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

mbillard
mbillard

Reputation: 38882

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.

Upvotes: 1

toddk
toddk

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

Bill Martin
Bill Martin

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

jlew
jlew

Reputation: 10601

Shouldn't DropDownList1 and DropDownList2 be in quotes?

Upvotes: 1

MikeW
MikeW

Reputation: 5922

case sensitive: document.getElementById?

Upvotes: 1

Related Questions