JavaScript gets the value of Radio selected

  • 2020-10-31 21:36:24
  • OfStack

The principle is as follows: 1 generally use the method of traversal to determine whether each Radio is selected, and if so, take its value.


<form id="userlist" method="post" action="option.php">
<input type="radio" name="userid" value="1">1
<input type="radio" name="userid" value="2">2
<input type="radio" name="userid" value="3">3
</form>
<script language="javascript">
function usubmit(action){
var radionum = document.getElementById("userlist").userid;
for(var i=0;i<radionum.length;i++){
if(radionum[i].checked){
userid = radionum[i].value
}
}
window.location.href='option.php?action='+action+'&userid='+userid;
}
</script>

Note that id (userlist) is set in form

There are two things to note here: how does one evaluate, and how does one traverse
document.getElementById("userlist").userid;
This is how to take the name value of a control element based on form's id.
It can also be obtained directly with document.getElementsByName ("userid")

The difference between getElementById and getElementsByName is that when getElementById takes radio type element, only a single control can be selected; when getElementsByName takes radio type element, the entire radio array is taken out; if 1 must use getElementById, then id of the entire form can be obtained with getElementById, as shown in code 1 above. The radio name will follow

We now know that document.getElementsByName ("userid") is an array of 1, and that the elements in the array are all the elements in the dom tree where name is radionum, even if there is only 1 radio, it is an array of 1 element.
document.all.userid, on the other hand, is a reference to the userid element in the page. When there are more than one radio in the page, it returns an array. If the page contains only one radio, it will get a reference to the radio object. Since you don't get an array, you can't iterate through the groups.

Make the function as follows:


function  getRadioBoxValue(radioName) 
{ 
      var obj = document.getElementsByName(radioName); // This one is labeled name To take control 
         for(i=0; i<obj.length;i++)  {

         if(obj[i].checked)  { 
             return  obj[i].value; 
         } 
       }     
       return "undefined";    
}

JS gets the selected value in radio


function Foo()
{
  var selectedIndex = -1;
  var form1 = document.getElementById("form1");
  var i = 0;
  
  for (i=0; i<form1.r.length; i++)
  {
    if (form1.r[i].checked)
    {
      selectedIndex = i;
      alert(" You select the option of  value  Is this: " + form1.r[i].value);
      break;
    }
  }
  
  if (selectedIndex < 0)
  {
    alert(" You did not select any items ");
  }
}

Related articles: