0

i have used this code to set a validation on a form to gives me alert when NOT all the buttons has checked! .. but when i try it , it gives me error alert even when all buttons checked .. help please ?

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>

    <script type="text/javascript">
function validateForm(formData){
    if(!this.v1.checked && !this.v2.checked && !this.v3.checked){
        alert('answer all questions please');
        return false;
    }
       return true;
    }
    </script>

    <title></title>
</head>

<body>
    <form name="form1" action="mark.php" onsubmit="return validateForm()" method="post"> 
        <input type="radio" value="1" id="v1" name="v1"> <input type="radio" value="1" id="v2" name="v2"> <input type="radio" value="1" id="v3" name="v3"> <input type="submit" value="Send">
    </form>
</body>
</html>
Jonas
  • 121,568
  • 97
  • 310
  • 388
user1806136
  • 35
  • 1
  • 4
  • 13

2 Answers2

1

Take a look what is this refering to, using console.log(this).

Maybe is better if you get the radio buttons using getElementById(), look an example here.

How can I check whether a radio button is selected with JavaScript?

Also change the logic of your if statement, use this:

if (!document.getElementById('v1').checked || !document.getElementById('v2').checked || !document.getElementById('v3').checked)

I modified your script in jsfiddle.net, to make a working one: http://jsfiddle.net/Xh5HW/1/

Community
  • 1
  • 1
Memochipan
  • 3,405
  • 5
  • 35
  • 60
  • @user1806136, I think is a problem selecting the right element. It seems that you're not really checking the radio buttons in your if statement. Please review carefully the link above. – Memochipan Nov 16 '12 at 07:14
  • @user1806136, you have also a problem with the logic of the if statement. I added code you can use to my answer. – Memochipan Nov 16 '12 at 07:28
  • i hve used document.getElementById as u said it still doesnt work and also didn't give me alert box it just go to next page! – user1806136 Nov 16 '12 at 07:44
0
var btn = valButton(form.group1);
if (btn == null) alert('No radio button selected');
else alert('Button value ' + btn + ' selected');

chek out http://javascript.about.com/library/blradio.htm

rOcKiNg RhO
  • 631
  • 1
  • 6
  • 16