Guddu
Guddu

Reputation: 627

Alert message in ASP.NET

I am new to ASP.NET programming. I need to display a message if RadioButton is not clicked. I have already written JavaScript for the onclick event to handle single selection.

My code:

if(rbTest.Checked == true)
{
        //my code
}
else
{
    string message = "Please select case to download";
    lnkbtnDownload.Attributes.Add("onclick", "alert('" + message + "');return false;");
}

This keeps on displaying alert message even if I have selected a radio button. Why?

Upvotes: 1

Views: 4092

Answers (4)

Vikas
Vikas

Reputation: 24322

use

var r = documet.getElementById("rbTest")

and then compare with r[0].checked

use index, because radiobutton r can be an array

Upvotes: 0

rahul
rahul

Reputation: 187020

You have to check whether the radio button is clicked or not inside the onclick handler for the lnkbtnDownload.

lnkbtnDownload.Attributes.Add("onclick","if(!document.getElementById('rbTest').checked))alert('message')");

Upvotes: 4

Cerebrus
Cerebrus

Reputation: 25775

You need to understand the difference between server-side code and client-side code. Your code is written in C# which runs on the server. Here is what I assume is happening:

a. Your page renders for the first time and the user does not choose the relevant radiobutton. He/she then submits the page (possibly via the LinkButton).

b. Your page submits and the code you pasted runs on the server. You check if the radiobutton is checked. If not, you add an attribute to a LinkButton so that when the LinkButton is clicked, it will raise an alert.

c. Your page renders after postback with the new attribute added to the LinkButton.

d. On the click of the LinkButton, you get an alert with the message. Since you have set it to return false, the page will not submit again and will keep on showing you the alert.

Do you see what's happening here? Your alert condition needs to be checked on the client itself. The snippet provided by @Phoenix should be a good starting point.

Upvotes: 2

cgp
cgp

Reputation: 41381

This is relatively ugly but would do the trick:

<script>
  var rbSelected = false;
</script>

<form onsubmit="if (!rbSelected) { alert('You must select something!";return false}">
 <input type="radio" name="rbTest" onclick="rbSelected=true" value=1>a
 <input type="radio" name="rbTest" onclick="rbSelected=true" value=2>b
 <input type="radio" name="rbTest" onclick="rbSelected=true" value=3>c
 <input type="submit value="Submit">
</form>

If you've got more than one radio button (which I'm hoping you do), then you really can't use getElementById without all this extra looping logic etc... This avoids the looping.

See example: http://jsbin.com/edoke

Upvotes: 0

Related Questions