Reputation: 135
I'm using this snippet to calculate how many check boxes a user clicks on, I then have a submit button underneath where I'm trying to get it to display the percent. For example, if they clicked on 8 checkboxed out of 10, then it should display 80% underneath.
I tried the following bit of PHP code
$x = "<?php if(isset($_POST['count-checked-checkboxes']))?>";;
$total = 500;
$percentage = ($x*100)/$total;
where x would be the number of checkboxes checked but when I tried to echo $percentage I got an underfined variable error: Notice: Undefined variable: percentage"
Is there was I can do this using Javascript or Jquery perhaps?
Upvotes: 0
Views: 115
Reputation: 26460
PHP doesn't know how many checkboxes there are. You can do this in jQuery instead, and if you need it in PHP, set a hidden element that sends the total number of checkboxes.
<div class="count-checkboxes-wrapper">
<span id="count-checked-checkboxes">0</span> of
<span id="count-total-checkboxes">0</span>
(<span id="percentage-checked-checkboxes">0</span> %) checked
</div>
If you need to send the total number of checkboxes to PHP, you can add a hidden input element within your form
<input type="hidden" id="checkedCheckboxesPercentageInput" name="checkedCheckboxesPercentage" value="0" />
$(document).ready(function(){
var $checkboxes = $('#devel-generate-content-form td input[type="checkbox"]')
$("#count-total-checkboxes").text($checkboxes.length);
$checkboxes.change(function(){
var countCheckedCheckboxes = $checkboxes.filter(':checked').length,
percentageCheckedCheckboxes = countCheckedCheckboxes / $checkboxes.length * 100;
$('#count-checked-checkboxes').text(countCheckedCheckboxes);
$("#percentage-checked-checkboxes").text(percentageCheckedCheckboxes);
// If you're sending it to PHP, add the hidden input and uncomment below
// $("#checkedCheckboxesPercentageInput").val($checkboxes.length);
});
});
If you add the hidden element, you can then get the value in PHP through $_POST['checkedCheckboxesPercentage'];
.
See your revised fiddle https://jsfiddle.net/4mrjyxod/
Upvotes: 0
Reputation: 16741
Yes, you can do this with Javascript:
$checkboxes.change(function(){
var countCheckboxes = $checkboxes.length;
var countCheckedCheckboxes = $checkboxes.filter(':checked').length;
var percentage = Math.round(100 * countCheckedCheckboxes / countCheckboxes);
$('#percentage-checked-checkboxes').text(percentage);
});
See: jsFiddle
However, the percentage won't be known on the server now.
Upvotes: 1