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?
With jQuery, it'd be something like
Let me break that down into pieces to cover it more clearly. jQuery processes things from left to right.
input
limits it to input tags.[name=gender]
limits it to tags with the name gender within the previous group.:checked
limits it to checkboxes/radio buttons that are selected within the previous group.If you want to avoid this altogether, mark one of the radio buttons as checked (
checked="checked"
) in the HTML code, which would guarantee that one radio button is always selected.If you want vanilla JavaScript, don't want to clutter your markup by adding IDs on each radio button, and only care about modern browsers, the following functional approach is a little more tasteful to me than a for loop:
If neither is checked, it will return
undefined
(though you could change the line above to return something else, e.g., to getfalse
returned, you could change the relevant line above to:}).pop() || {value:false}).value;
).There is also the forward-looking polyfill approach since the RadioNodeList interface should make it easy to just use a
value
property on the list of form child radio elements (found in the above code asformElement[radioName]
), but that has its own problems: How to polyfill RadioNodeList?This would be valid for radio buttons sharing the same name, no JQuery needed.
If we are talking about checkboxes and we want a list with the checkboxes checked sharing a name:
HTML Code
Javascript Code:
Let's pretend you have HTML like this
For client-side validation, here's some Javascript to check which one is selected:
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.
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.