开发者

JavaScript function checked if a radio button is selected

开发者 https://www.devze.com 2023-02-15 03:48 出处:网络
<label for=\"Merital Status\">Marital Status:</label> <input type=\"radio\" title=\"Marital Status\" name=\"Marital_Status\" id=\"Marital Status\" value=\"Single\"/>Single
<label for="Merital Status">Marital Status:</label>
    <input type="radio" title="Marital Status" name="Marital_Status" id="Marital Status" value="Single"/>Single
    <input type="radio" title="Marital Status" name="Marital_Status" value="Married"/>Married
    <input type="radio" title="Marital Status" name="Marital_Status" value开发者_运维百科="Divorced"/>Divorced

And I want to write a JavaScript function that checks whether a radi button named "Merital_Status" is selected. I represent the function that I wrote for this purpose. The function gets as an argument the element id and returnes boolen:

function radio_button_checker(elemId)
{
    var radios = document.getElementsByTagName(elemId);

    var value = false;


    for (var i = 0; i < radios.length; i++) 
    {

        if (radios[i].checked) 
        {

            value = true;
            break;
        }
    }
    return value;
}

And I invoke this function like this:

if (radio_button_checker('Marital_Status') == false) 
{
    alert('Please fill in your Merital Status!');
    return false;
}

But it does not work. Please tell me how to modify my function in order to check if radiobutton is checked.


What you are doing is looking for an element with the tag name "Merital_Status". Replace document.getElementsByTagName with document.getElementsByName and it should work.


You are mixing ID's and NAME's.

Your radio button "set" needs to all have the same name (which you have), and if you need to refer to them individually by id, then you'll need to add an id to the last two (currently not set... and not required if you apply the labels to each individual option). You will want the label tags for each radio button as it improves the usability by allowing the user to click on the word not just the small radio button.

Marital Status:
  <label><input type="radio" name="Marital_Status" value="Single"/>Single</label>
  <label><input type="radio" name="Marital_Status" value="Married"/>Married</label>
  <label><input type="radio" name="Marital_Status" value="Divorced"/>Divorced</label>

However when you test... you want to see that at least 1 radio in the set is checked. You can do this with:

function radioButtonChecker(fieldNAME){
  var radioSet = document.forms[0].elements[fieldName];
  for(var i=0;i<radioSet.length;i++){
    if(radioSet[i].checked){
      return true;
    }
  }
  return false;
}

There are a few presumptions made here.

  1. You always have more than 1 radio button in the set
  2. Your form is the 1st (index 0) form... if not you'll need to adjust the radioSet lookup
0

精彩评论

暂无评论...
验证码 换一张
取 消