How can I check whether a radio button is selected with JavaScript?

前端 未结 28 2438
面向向阳花
面向向阳花 2020-11-22 00:58

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?

28条回答
  •  甜味超标
    2020-11-22 01:35

    With jQuery, it'd be something like

    if ($('input[name=gender]:checked').length > 0) {
        // do something here
    }
    

    Let me break that down into pieces to cover it more clearly. jQuery processes things from left to right.

    input[name=gender]:checked
    
    1. input limits it to input tags.
    2. [name=gender] limits it to tags with the name gender within the previous group.
    3. :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.

提交回复
热议问题