1

How can I check checkboxes checked property? If any of them is not checked, display this sentence in span: "you shoud select one of them". My validation don't work.

<label>
    <input type="checkbox" name="chk[]" id="chk[]" />male
</label>
<label>
    <input type="checkbox" name="chk[]" id="chk[]" />female
</label>

<script>
    if ($('input[name="chk[]"]:checked').length < 0) {
        $("#textspan").html('you shoud select one of them');
    }
</script>
Zanon
  • 29,231
  • 20
  • 113
  • 126
Elham Bagheri
  • 253
  • 7
  • 21
  • 1
    Change `< 0` to `=== 0` – PitaJ Aug 17 '14 at 16:08
  • 1
    I don't think a length can be less than `0`, and why are you using checkboxes instead of `radio` input elements for this (mutually-exclusive) choice? – David Thomas Aug 17 '14 at 16:13
  • This question/answer will help http://stackoverflow.com/questions/2204250/check-if-checkbox-is-checked-with-jquery – Cory Aug 17 '14 at 16:13

2 Answers2

0

As far as your specific question goes, when no checkbox is checked $('input[name="chk[]"]:checked').length is 0, not negative - so you should change the condition from if ($('input[name="chk[]"]:checked').length < 0) to if ($('input[name="chk[]"]:checked').length == 0)

Full example

Other than that, some side notes: 1. I'd use radio buttons (as it is more suitable for your current male / female selection). 2. You have the same ID (chk[]) twice, which renders your HTML invalid. 3. The [] characters in the ID are not permitted in HTML 4.1 standards, and do not suit the convention.

Noy
  • 1,258
  • 2
  • 11
  • 28
0

I took the liberty of changing the code a bit, as your HTML is a bit strange.

Working example: http://jsfiddle.net/a4jzvoou/

HTML:

<div>
    <input type="checkbox" class='gender' id="male">male</input>
    <input type="checkbox" class='gender' id="female">female</input>
</div>
<button class="validate">Validate</button>

JS:

$(function() {
  $('.validate').click(function(event) {     
     var checkedCount = ($('input[class="gender"]:checked').length))        
  })   
});
bitoiu
  • 6,893
  • 5
  • 38
  • 60