I have two radio buttons within an HTML form. A dialog box appears when one of the fields is null. How can I check whether a radio button is selected?
What you should do is set up two variables, both of them serving as boolean flags. Then loop through each set of radio buttons in order to determine if a button has been selected. If so, set the corresponding flag to true, otherwise false. Then at the end, test to see if both flags have been set to true.
Let's pretend you have HTML like this
<input type="radio" name="gender" id="gender_Male" value="Male" /> <input type="radio" name="gender" id="gender_Female" value="Female" />
For client-side validation, here's some Javascript to check which one is selected:
if(document.getElementById('gender_Male').checked) { //Male radio button is checked }else if(document.getElementById('gender_Female').checked) { //Female radio button is checked }
The above could be made more efficient depending on the exact nature of your markup but that should be enough to get you started.
If you're just looking to see if any radio button is selected anywhere on the page, PrototypeJS makes it very easy.
Here's a function that will return true if at least one radio button is selected somewhere on the page. Again, this might need to be tweaked depending on your specific HTML.
function atLeastOneRadio() { return ($('input[type=radio]:checked').size() > 0); }
For server-side validation (remember, you can't depend entirely on Javascript for validation!), it would depend on your language of choice, but you'd but checking the gender
value of the request string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With