How can we access the value of a radio button using the DOM?

后端 未结 12 1870
鱼传尺愫
鱼传尺愫 2020-12-05 15:25

How can we access the value of a radio button using the DOM?

For eg. we have the radio button as :



        
相关标签:
12条回答
  • 2020-12-05 15:38

    If you need the selected one, most frameworks support functionality like this:

    //jQuery
    $("input[name='sex']:checked").val()
    
    0 讨论(0)
  • 2020-12-05 15:44
    function getEleByName(){
        if(true==document.getElementsByName('gender')[0].checked){
            alert('selected gender is: male');
        }
        else{
            alert('selected gender is: female');
        }
    }
    
    0 讨论(0)
  • 2020-12-05 15:48

    There are a couple of ways.

    1. Put an id on each input

    <input name="sex" id="sex_male" type="radio" value="male">
    <input name="sex" id="sex_female" type="radio" value="female">
    

    Then you can use document.getElementById("sex_male")

    2. Use something like PrototypeJS (jQuery works too)

    Then you can do something like this:

    //This loops over all input elements that have a name of "sex"
    $$('input[name="sex"]').each( function(elem) {
      //Do something
    });
    

    Or even this to get at just the "male" radio button:

    $$('input[name="sex"][value="male"]').each(function(elem) {
      //Do something
    });
    

    An easy way to get started with Prototype is include it from Google by adding this between the <head></head> tags of your page:

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.3/prototype.js"></script>
    
    0 讨论(0)
  • 2020-12-05 15:48

    If you use document.form1.sex, you are returned an array.

    document.form1.sex[0] = first radio button

    document.form1.sex[1] = second radio button

    To check which is checked you need to loop:

    whoChecked(document.form1.sex)
    
    function whoChecked(fieldName) {
       for(var x=0;x<fieldName.length;x++) {
         if(fieldName[x].checked) {
            return fieldname[x].value
         }
    }
    
    0 讨论(0)
  • 2020-12-05 15:49

    Surprised no-one has suggested actually using the Selector API:

    document.querySelector('input[name=sex]:checked').value
    

    Browser support is good

    0 讨论(0)
  • 2020-12-05 15:51

    If you want the selected one, but don't have a framework handy, you can iterate over the element array looking for whichever one is checked:

    for (var i = 0; i < document.form1.sex.length; i++) {
        if (document.form1.sex[i].checked) alert(document.form1.sex[i].value);
    }
    
    0 讨论(0)
提交回复
热议问题