jquery - PHP - Checkbox saving value to Database -
i have few checkbox in form , i'm setting each value if checked or unchecked. checkbox checked has value of true , unchecked false if have of checkbox checked(value true) , unchecked 1 of them, other checkbox unchecked , value on database become false. can't understand behavior below code
html
<label><input type="checkbox" id="trans_val_identical" value="false">ii transaction value of identical goods</label> <label><input type="checkbox" id="trans_val_identical" checked="checked" value="false">ii transaction value of identical goods</label> </div> <div class="checkbox"> <label><input type="checkbox" id="trans_val_similar" value="false">iii transaction value of similar goods</label> <label><input type="checkbox" id="trans_val_similar" checked="checked" value="false">iii transaction value of similar goods</label> </div> <div class="checkbox"> <label><input type="checkbox" id="deductive_val" value="false">iv deductive value</label> <label><input type="checkbox" id="deductive_val" checked="checked" value="false">iv deductive value</label> </div> <div class="checkbox"> <label><input type="checkbox" id="computed_val" value="false">v computed value</label> <label><input type="checkbox" id="computed_val" checked="checked" value="false">v computed value</label> </div> <div class="checkbox"> <label><input type="checkbox" id="fallback_val" value="false">vi fallback value</label> <label><input type="checkbox" id="fallback_val" checked="checked" value="false">vi fallback value</label> js
$('#trans_val_identical').change(function(){ if($(this).attr('checked')){ $(this).val('true'); }else{ $(this).val('false'); } }); $('#trans_val_similar').change(function(){ if($(this).attr('checked')){ $(this).val('true'); }else{ $(this).val('false'); } }); $('#deductive_val').change(function(){ if($(this).attr('checked')){ $(this).val('true'); }else{ $(this).val('false'); } }); $('#computed_val').change(function(){ if($(this).attr('checked')){ $(this).val('true'); }else{ $(this).val('false'); } }); $('#fallback_val').change(function(){ if($(this).attr('checked')){ $(this).val('true'); }else{ $(this).val('false'); } });
there couple of issues here:
the first checkbox elements don't have names, means aren't going passed server values. make sure have names can refer them in php script , save them database.
second, understanding of how checkboxes submitted in form bit off. value attribute of checkbox submitted if it's checked, , it's not submitted if it's unchecked. shouldn't change value true false or vice-versa.
so if have this:
<input type="checkbox" name="trans_val_identical" value="1"> then $_post['trans_val_identical'] (assuming you're using post submit form) "1" if checkbox checked, , non-existent if checkbox unchecked. check if checkbox checked in php, you'd use this:
if ( isset( $_post['trans_val_identical'] )) { // checkbox checked } else { // checkbox not checked }
Comments
Post a Comment