Rosamunda
Rosamunda

Reputation: 14980

JS validation, why this code won´t work?

I can´t get the validation in JS, and don´t understand why it doesn´t work. The user should get an alert if at least one of the checkboxes isn´t checked. It doesn´t work, because the form gets submitted ok even if if none checkboxes are checked.

<body>
<script>
function validar()
{
var s1=document.getElementById('s1');
var s2=document.getElementById('s2');

if (s1.value==''||s2.value=='')
  {
  alert("You must check at least one!");
  return false;
  }
}
</script>

<form name="calcular" onsubmit="return validar()" method="post">
<input type ="checkbox" name="servicios[]" id="s1" value="sinservicios">Sin servicios<br>
<input type ="checkbox" name="servicios[]" id="s2" value="dosservicios">Dos servicios<br>

...

Upvotes: 0

Views: 71

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

You may try using the checked property to ensure that at least one of the 2 checkboxes is checked:

<script>
    function validar() {
        var s1 = document.getElementById('s1');
        var s2 = document.getElementById('s2');

        if (!s1.checked && !s2.checked) {
            alert('You must check at least one!');
            return false;
        }
        return true;
    }
</script>

Also notice we should return true in case the validation succeeds.

The reason why your code doesn't work is because you have used the value property. That's always gonna return the value attribute of your checkbox (sinservicios or dosservicios) no matter if the user checked or not this checkbox. It will never return an empty string which is what you seem to be testing for in your if condition.

Upvotes: 5

Related Questions