Joffrey Joffrey - 10 days ago 7
PHP Question

How to display the value of hidden when checkbox is checked in PHP

Im having problem on how to get the value of the hidden input box once the checkbox is checked. here are my code.

<label class="control control--checkbox"><span>Additional</span>
<input type="checkbox" name="apply[]" value=""/>
<input type="hidden" name="option[]" value="1 bottle"/>
<input type="hidden" name="cost[]" value="$20"/>
</label>
<label class="control control--checkbox"><span>Additional</span>
<input type="checkbox" name="apply[]" value=""/>
<input type="hidden" name="option[]" value="3 bottle"/>
<input type="hidden" name="cost[]" value="$50"/>
</label>


My Php code:

<?php
$options = $_POST['option'];
$costs = $_POST['cost'];
$apply = $_POST['apply'];
if (isset($apply)) {
foreach ($options as $option) {
echo '<tr>';
echo '<td>'.$option.'</td>';
echo '</tr>';
}
}
?>


It seems that the option of my php code is always two, i want only to display that was checked and dont display that are not.

can someone advise me on how can i solve this problem or any work around to get the same result?

Answer

Using PHP you need to set the CheckBox value and then are able to find the other values.

<input type="checkbox" name="apply[]" value="y"/>

PHP

$options = $_POST['option'];
$costs = $_POST['cost']; 
$apply = $_POST['apply'];
if(isset($apply)) {
    foreach ($options as $key => $option) {
        if($option == 'y'){
            echo $costs[$key];
            echo $apply[$key];
        }
    }
}

Using jQuery you can get the Hidden values like-

$(function(){
    $('.input_check').on("change", function(){
    var chk = $(this).prop('checked');
    if(chk == true){
        var val = $(this).closest('label').find('.option').val();
        console.log(val);
    }
  })
})