开发者

validation of radiobuttons

开发者 https://www.devze.com 2022-12-14 21:10 出处:网络
how to add validation to check whether the user has chosen between two radio buttons? Suppose ther开发者_运维问答e are 2 radio buttons; male and female. How can we ensure that the user has selected on

how to add validation to check whether the user has chosen between two radio buttons? Suppose ther开发者_运维问答e are 2 radio buttons; male and female. How can we ensure that the user has selected one of them?


This question is tagged ASP.NET, unless I am missing something, wouldn't a RadioButtonList with a RequiredFieldValidator be ideal ? Seems like the OP is new to web dev, so this may be the easiest.


You can use a name for the radio buttons and then use the following

function CheckState()
{
    var rad = document.getElementsByName ( "rdToCheck" );
    var isChecked = false;

    for ( var i = 0;i < rad.length; i++ )
    {
        if ( rad[i].checked == true )
        {
            isChecked = true;
            break;
        }
    }

    if ( !isChecked )
    {
        alert ( "Please select an option" );
    }
}

<input type="radio" id="rd1" name="rdToCheck" />
<input type="radio" id="rd2" name="rdToCheck" />

<button id="btn1" onclick="CheckState();">Click</button>


Use the property ValidationGroup="radiobuttons" and in your code behind's method, do:

Page.Validate("radiobuttons");
if (Page.IsValid)
{
  // do some code
}

More info and examples can be found here.


Use javascript,

if(document.getElementById("ur1stradiobuttonID").checked== false &&
  document.getElementById("ur2ndradiobuttonID").checked== false)
 {
  alert("Select an option");
  return false;
  }
  else
    return true;


I would add a javascript validation to the form with an onsubmit and then check the buttons in the javascript function

<form onsubmit="return checkButtons();" >

<script>
function checkButtons() {
   if (document.form1.myRadioButton[0].checked != true && 
         document.form1.myRadioButton[1].check != true )
{
    alert('select a button');
    return false;
}

}
</script>


my option will be, have one radio checked by default (e.g male). then u do not need to validate whether one has been checked.

0

精彩评论

暂无评论...
验证码 换一张
取 消