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

前端 未结 28 2474
面向向阳花
面向向阳花 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:47

    Note this behavior wit jQuery when getting radio input values:

    $('input[name="myRadio"]').change(function(e) { // Select the radio input group
    
        // This returns the value of the checked radio button
        // which triggered the event.
        console.log( $(this).val() ); 
    
        // but this will return the first radio button's value,
        // regardless of checked state of the radio group.
        console.log( $('input[name="myRadio"]').val() ); 
    
    });
    

    So $('input[name="myRadio"]').val() does not return the checked value of the radio input, as you might expect -- it returns the first radio button's value.

提交回复
热议问题