cyberwebdev
cyberwebdev

Reputation: 69

javascript is not taking all values from html and php

javascript is only taking first checkbox value it is not taking other checkbox value why ? HTML:

<input type="checkbox" id="checkbox" onclick="check()" value="<?php echo $data->id; ?>  " >

Javascript:

    function check()
     {    
          var id = $('#checkbox').attr('value')

         var checkbox = document.getElementById('checkbox');
        if(checkbox.checked==true)  {
            alert(id);
        }
        else
        {
            alert('false');
        }

     }

Upvotes: 1

Views: 67

Answers (2)

Lemon Kazi
Lemon Kazi

Reputation: 3311

you can try like this with jQuery. here in console you can see all checked value is displaying after click

$(document).ready(function() {
  var ckbox = $("input[name='checkbox']");
  var chkId = '';
  $('input').on('click', function() {
    
    if (ckbox.is(':checked')) {
      $("input[name='checkbox']:checked").each ( function() {
   			chkId = $(this).val() + ",";
        chkId = chkId.slice(0, -1);
 	  });
       
       console.log( $(this).val() ); // return all values of checkboxes checked
       //console.log(chkId); // return value of checkbox checked
    }     
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox" value="12520">
<input type="checkbox" name="checkbox" value="12521">
<input type="checkbox" name="checkbox" value="12522">

Upvotes: 2

Raghul Ramkish
Raghul Ramkish

Reputation: 5

Try this instead.

$("'#checkbox").live("click", function () {

 $("input:checkbox[name=chk]:checked").each(function () {

  alert("Id: " + $(this).attr("id") + " Value: " + $(this).val());

   });

  });

Upvotes: 0

Related Questions