0

code:

<script>
    $(document).ready(function(){
        for(id=1;id<=31;id++)
        {
            $("#"+id).click(function(){
                console.log($('.state:checked').map(function() {
                    ids = this.value;
                }).get().join(', '));
                alert(ids);
            });
        }
    });
</script>

<?php 
    $sql2 = "select * from statemaster";
    $row1 = mysqli_query($link,$sql2);
    while ($fetch1 = mysqli_fetch_array($row1)) 
    {
?>
    <input type="checkbox" name="statename" id="<?php echo $fetch1['stateid']; ?>" value="<?php echo $fetch1['stateid']; ?>" class="state">&nbsp;<?php echo $fetch1['statename']; ?><br/>
<?php           
    } 
?>

In this code I am using map function and want to get multiple ids of state like 1,2,3,4 but still when I click on any state it alert ids one by one like on check 1st check box it alert 1 similarly on second it gives 2 but I want like 1,2,3,4. So, How can I do this ?please help me.

Thank You

randy
  • 3
  • 1

2 Answers2

0

You aren't returning anything in the map(). You only assign each value to a global variable in each iteration of the loop. Thus what you alert is the last value

Try

$("#" + id).click(function() {

  var ids = $('.state:checked').map(function() {
    return this.value;
  }).get().join(', ');

  console.log(ids);
  alert(ids);
});
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • `$(".state").change(function () {` would be better instead of `$("#" + id).click(function() {` – Satpal Jun 02 '17 at 11:09
0

I don't have the reputation to comment so I have to write here. It seems you need each not map for your requirement and You can refer this jQuery map vs. each to check your requirment.

Anshul
  • 464
  • 4
  • 14