0

i have two radio button for selecting gender. and used below JS but if 'female' button is selected it takes it but if 'male' is selected it showing that none is selected.

var r = document.getElementsByName("sex")
var sex= -1;
for(var i=0; i <= r.length; i++)
    {
         if(r[i].checked)
            {
            sex = i; 
            }
    if (sex == -1)
    { 
        alert("please select gender");
        return false;
    }    
}

i have taken two div for two radio with same name for both radio. so here is my html to check if problem is there,

<div style="margin-top:17px; width:92px;float:left;">
   <input id="female" class="radio" type="radio" name="sex" value="female">Female</input>
</div>
<div style="margin-top:17px; width:92px;float:left; margin-bottom:17px;">
   <input class="radio" id="male" type="radio" name="sex" value="male">Male</input>
</div>

2 Answers 2

1

There where some issues.

  • JavaScript is zero-index based. You ran a loop with i <= r.length, this means that your loop will go outside the node list's boundary. It iterates three times, where it should iterate only two times.
  • The if statement is in the for loop, it should be outside, since it should only be executed once.

function validate()
{

  var r = document.getElementsByName("sex")

  var sex= -1;
  for(var i=0; i < r.length; i++)
    {
         if(r[i].checked)
         {
            sex = i; 
            break;
         }
    }
    if (sex < 0)
    { 
        alert("please select gender");
        return false;
    }
}

document.querySelector("button").addEventListener("click", validate, false);
<div style="margin-top:17px; width:92px;float:left;">
   <input id="female" class="radio" type="radio" name="sex" value="female">Female</input>
</div>
<div style="margin-top:17px; width:92px;float:left; margin-bottom:17px;">
   <input class="radio" id="male" type="radio" name="sex" value="male">Male</input>
</div>

<button>Validate</button>

Sign up to request clarification or add additional context in comments.

4 Comments

i dont know much about use of snippet but , this showing to select a gender when trying to validate after selecting male.
@sajansahoo found some issues I overlooked in your original code. Try it now.
'need to be in the same container to work' why this? The selection of this example is given by name and without any child-selectors.
@dsuess, wow a long time ago (yet somehow into the future) radios needed to be in the same container. This is no longer so, correct it.
0

Maybe you can simplify the logic and replace for-loop by an more explicit 'selected'-check. Furthermore, please note, to have clickable text labels for radio buttons, to use text, as it is non standard and would not work correctly with most browsers.

function validateFn() {
  if (document.querySelectorAll('[name=sex]:checked').length == 0) {
    alert('please select a sex')
  }
}

document.querySelector('[type=button]').addEventListener('click',validateFn, false);
<form>
  <div>
    <input id="female" class="radio" type="radio" name="sex" value="female" />
    <label for="female">Female</label>
  </div>
  <div>
    <input class="radio" id="male" type="radio" name="sex" value="male" />
    <label for="male">Male</label>
  </div>
  <input type="button" value="validate"/>
</form>

This code will select all elements with name = sex, which are selected. In case of radio buttons this only can be one or nothing. For this selection query "document.querySelectorAll" is used, which is quit mor powerfull than getElementByName/Id/ClassName..., see http://www.w3schools.com/Jsref/met_document_queryselectorall.asp. Also, the selection uses "pseudo-states" or "pseudo-classes", see http://www.w3schools.com/css/css_pseudo_classes.asp

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.