0

Anyone can please help me why it returning an empty array. and thanks in advance. you can check code on http://newseinstein.com/Rwork/index.php/Listing.

Code sample :

function search(){
  var pettype = [];
  
  $(".pettype :checked").each(function(){
      alert($(this).val());
      pettype.push($(this).val());
  })
  
  alert(pettype);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="checkbox" name="type[]" class="pettype" value="Lost" onclick="search();">
<input type="checkbox" name="type[]" class="pettype" value="Found" onclick="search();">
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101

2 Answers2

0

You should just remove the extra space in the following line :

$(".pettype :checked").each(function(){
___________^

Should be :

$(".pettype:checked").each(function(){

Else the selector will serch for checked elements inside .pettype elements.

Hope this helps.

function search(){
  var pettype = [];
  $(".pettype:checked").each(function(){
      console.log($(this).val());
      pettype.push($(this).val());
  })
  alert(pettype);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="checkbox" name="type[]" class="pettype" value="Lost" onclick="search();">
<input type="checkbox" name="type[]" class="pettype" value="Found" onclick="search();">

I suggest to attach the event in the JS code instead of inline attachement, like :

$('.pettype').on('change', function(){
  var pettype = [];
  $(".pettype:checked").each(function(){
      pettype.push($(this).val());
  })
  console.log(pettype);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="checkbox" name="type[]" class="pettype" value="Lost" />
<input type="checkbox" name="type[]" class="pettype" value="Found" />
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
-1

actually i think you made a very tiny mistake... you had $(".pettype :checked") but it has to be $(".pettype:checked") because otherwise jQuery is searching for a checked element that is a child of pettype and not actually pettype :)

function search(){
    var pettype = [];
    $(".pettype:checked").each(function(){
        pettype.push($(this).val());
    })
    alert(pettype);
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
HTML Code:

<input type="checkbox" name="type[]" class="pettype" value="Lost" onclick="search();">
<input type="checkbox" name="type[]" class="pettype" value="Found" onclick="search();">
FalcoB
  • 1,333
  • 10
  • 25