简体   繁体   中英

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?

您必须检查在lnkbtnDownload的onclick处理程序中是否单击了单选按钮。

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

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.

use

var r = documet.getElementById("rbTest")

and then compare with r[0].checked

use index, because radiobutton r can be an array

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM