PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 30, 2022

[FIXED] How can I vaildate radio buttons?

 July 30, 2022     javascript, radio-button, validation     No comments   

Issue

How i put validation on check box?

Here is my code:

<script>
function Validate(){
   var cntct = document.getElementById("contact").value;
   if (cntct.value=="")
   {
      alert("Please select contact medium");
      return false;
   }
}
</script>

<input type="radio" name="contact" id="contact" value="SMS">
<label>SMS</label> <input type="radio" name="contact" id="contact" value="CALL">
<label>CALL</label> <input type="radio" name="contact" id="contact" value="EMAIL">
<label>EMAIL</label>

please help..


Solution

in case of checkboxes and radiobuttons, the element is checked when the "checked" property is true:

function Validate(){
    var selectedValue = "";
    var cntct = document.getElementsByname("contact");
    for(var i=0;i<cntct.length;i++) {
        if (cntct[i].checked)
        {
            selectedValue = cntct.value;
        }
    }
    if(selectedValue == "") {
        alert("Please select contact medium");
        return false;
    }
    return true;
}

UPDATE

I just noticed that you have multiple elements with the same ID. This is not allowed, in such case the browser will return only the last element with that ID. You need to iterate over the elements with the same name and pick one with attribute checked. See the code above



Answered By - haynar
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing