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?
标签:
javascript
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
Give radio buttons, same name but different IDs.
This is also working, avoiding to call for an element id but calling it using as an array element.
The following code is based on the fact that an array, named as the radiobuttons group, is composed by radiobuttons elements in the same order as they where declared in the html document:
A vanilla JavaScript way
This code will alert the selected radio button when the form is submitted. It used jQuery to get the selected value.
The scripts in this page helped me come up with the script below, which I think is more complete and universal. Basically it will validate any number of radio buttons in a form, meaning that it will make sure that a radio option has been selected for each one of the different radio groups within the form. e.g in the test form below:
The RadioValidator script will make sure that an answer has been given for both 'test1' and 'test2' before it submits. You can have as many radio groups in the form, and it will ignore any other form elements. All missing radio answers will show inside a single alert popup. Here it goes, I hope it helps people. Any bug fixings or helpful modifications welcome :)
Here is the solution which is expanded upon to not go ahead with submission and send an alert if the radio buttons are not checked. Of course this would mean you have to have them unchecked to begin with!
Just remember to set the id ('radio1','radio2' or whatever you called it) in the form for each of the radio buttons or the script will not work.