JS check if checkbox is checked keep initial value - javascript

I have a form to update personal data with multiple checkboxes who can be initially checked or not.
<form method="post" id="up_mission">
<input checked type="checkbox" id="first">
<input type="checkbox" id="second">
<button class="btn btn-default" type="submit" id="update_mission<?php echo $id_mission ?>"</button>
</form>
and the JS:
$(function() {
$("form[id^='up_mission']").submit(function() {
var value1 = document.getElementById("first").checked;
var value2 = document.getElementById("second").checked;
$.post("update_mission.php", {value1: value1, value2:value2}, functon(data) { console.log(data) });
});
});
In update_mission.php there is a simple SQL query to update with news values and I also do var_dump($_POST); and the values printed for first and second are always the ones that I initially put in the <input> it doesn't matters if I uncheck or check the checkbox.
How can I fix it please?
Here is the part of the php file :
var_dump($_POST);
$first = $_POST['value1'];
$second = $_POST['value2'];
if ($first == "true") { $first = "on";}
else {$first = "0";}
if ($second == "true") { $second = "on";}
else {$second = "0";}
update_miss = "UPDATE table SET First = 'first', Second = 'second'[...] WHERE my_condition";
// I connect to my DB, and do the query, and there is no problem here
// I also have text input in my form and they update pretty well

Use $('#first').is(':checked') and $('#second').is(':checked') to detect state of checkbox.
$(function() {
$("form[id^='up_mission']").submit(function() {
var value1 = $('#first').is(':checked') ? 1 : 0;
var value2 = $('#second').is(':checked') ? 1 : 0;
$.post("update_mission.php", {value1: value1, value2: value2}, functon(data) { console.log(data) });
});
});

Related

Best way to append querystring to url when a checkbox is selected while saving checkbox state?

I am making a checklist form and currently i am able to append the value of the selected boxes to the url in I feel an inefficient way and the main issue is that the state of the checkbox doesnt save either so a user cant see what they checked or uncheck.
This is the html code
<form id="carForm" method="get">
<label>BMW</label>
<input type="checkbox" value="bmw" onChange="checkboxChanged()">
<label>mercedes</label>
<input type="checkbox" value="mercedes" onChange="checkboxChanged()">
<label>honda</label>
<input type="checkbox" value="honda" onChange="checkboxChanged()">
<label>toyota</label>
<input type="checkbox" value="toyota" onChange="checkboxChanged()">
</form>
This is the script to make the url
let form = document.getElementById("carForm")
let checkboxes = document.getElementsByTagName("input")
var vals = "";
let formSubmit = () => {
for (var i=0, n=checkboxes.length;i<n;i++)
{
if (checkboxes[i].checked)
{
vals = checkboxes[i].value
// append checkbox values to url
var url = window.location.href;
if (url.indexOf('?') > -1){
// if a paramter already exists, append using
url += `&make=${vals}`
}else{
url += `?make=${vals}`
}
window.location.href = url;
}
console.log(vals);
}
}
function checkboxChanged() {
formSubmit()
}
</script>
So for instance if kia and honda were selected the url would be
/inventory?make=kia&make=honda
So if this is inefficient whats a better way of doing this and how do i ensure the checkbox state is persisted after the page is reloaded I am using nodejs/expressjs on server side and ejs
var makes=[];
...
for (var i=0;i<checkboxes.length;i++) {
if (checkboxes[i].checked) makes.push(checkboxes[i].value);
}
...
url+='&makes='+makes.join(',');
This will give you a comma delimited list; you can string split it on the server side.
You should take a look at URLSearchParams. Using it, you could do something like this:
const searchParams = new URLSearchParams(location.search);
document.querySelector('input[type=checkbox]').forEach(cb => {
if (cb.checked) {
searchParams.append('make', cb.value)
}
});
location.href = location.href.replace(location.search, '?' + searchParams.toString())
I think that you should not define all the parametres of the url as make=..., but with ${vals}=checked. Then you can read it easily with php and just check the names that are defined, but you will have to define a name for your chackboxes.
Sorry for my approximative english, I am swiss and speak french.
If you have access to a server-side language, like PHP, use that to check the URL and auto-check the boxes when the page loads. Something along these lines:
<?php
$bools = [
"kia" => isset($_GET['kia']),
"bmw" => isset($_GET['bmw']),
"mercedes" => isset($_GET['mercedes']),
"toyota" => isset($_GET['toyota'])
];
?>
<form id="carForm" method="get">
<label>BMW</label>
<input type="checkbox" value="bmw" onChange="checkboxChanged()" <?= $bools['bmw'] ? 'checked' : '' ?>>
<label>mercedes</label>
<input type="checkbox" value="mercedes" onChange="checkboxChanged()" <?= $bools['mercedes'] ? 'checked' : '' ?>>
<label>honda</label>
<input type="checkbox" value="honda" onChange="checkboxChanged()" <?= $bools['honda'] ? 'checked' : '' ?>>
<label>toyota</label>
<input type="checkbox" value="toyota" onChange="checkboxChanged()" <?= $bools['toyota'] ? 'checked' : '' ?>>
</form>
Protip: In PHP, you can use value="car[]" in order to submit an array of values which will already be an array type in PHP!
If you don't have access to server-side, or you don't wish to use it, then check the URL on page-load:
window.onload = () => {
for (const el of checkboxes) {
// Check the URL's params:
// From link below
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get(el.value);
if (myParam != null) {
el.checked = true;
}
}
}
(Get URL params reference, there are more options with better support than what I used. I just used the simplest option)

Store multiple checkbox inputs in local storage

I have multiple checkbox inputs that look like this:
<input type="checkbox" id="box-1">
<input type="checkbox" id="box-2">
<input type="checkbox" id="box-3">
I want to store their values (checked or unchecked) in the browser's local store.
The javascript that I'm using to do this is:
function onClickBox() {
let checked = $("#box-1").is(":checked");
let checked = $("#box-2").is(":checked");
let checked = $("#box-3").is(":checked");
localStorage.setItem("checked", checked);
}
function onReady() {
let checked = "true" == localStorage.getItem("checked");
$("#box-1").prop('checked', checked);
$("#box-2").prop('checked', checked);
$("#box-3").prop('checked', checked);
$("#box-1").click(onClickBox);
$("#box-2").click(onClickBox);
$("#box-3").click(onClickBox);
}
$(document).ready(onReady);
The first part saves the checkbox's state on the click and the second part loads it when the page refreshes.
This works well if the lines for box 2 and 3 are removed, but I need it to work with all the checkboxes.
Your main issue here is that you're only storing a single value in localStorage, checked, which will be overwritten every time you check a different box. You instead need to store the state of all boxes. An array is ideal for this, however localStorage can only hold strings, so you will need to serialise/deserialise the data when you attempt to read or save it.
You can also simplify the logic which retrieves the values of the boxes by putting a common class on them and using map() to build the aforementioned array. Try this:
<input type="checkbox" id="box-1" class="box" />
<input type="checkbox" id="box-2" class="box" />
<input type="checkbox" id="box-3" class="box" />
jQuery($ => {
var arr = JSON.parse(localStorage.getItem('checked')) || [];
arr.forEach((c, i) => $('.box').eq(i).prop('checked', c));
$(".box").click(() => {
var arr = $('.box').map((i, el) => el.checked).get();
localStorage.setItem("checked", JSON.stringify(arr));
});
});
Working example
function onClickBox() {
let checked1 = $("#box-1").is(":checked");
let checked2 = $("#box-2").is(":checked");
let checked3 = $("#box-3").is(":checked");
localStorage.setItem("checked1", checked1);
localStorage.setItem("checked2", checked2);
localStorage.setItem("checked3", checked3);
}
function onReady() {
let checked1 = "true" == localStorage.getItem("checked1");
let checked2 = "true" == localStorage.getItem("checked2");
let checked3 = "true" == localStorage.getItem("checked3");
$("#box-1").prop('checked', checked1);
$("#box-2").prop('checked', checked2);
$("#box-3").prop('checked', checked3);
$("#box-1").click(onClickBox);
$("#box-2").click(onClickBox);
$("#box-3").click(onClickBox);
}
$(document).ready(onReady);
Of course you could simplify it further by doing
function onClickBox(boxNumber) {
let checked = $("#box-" + boxNumber).is(":checked");
localStorage.setItem("checked" + boxNumber, checked);
}
function onReady() {
[1, 2, 3].forEach( function(boxNumber) {
$("#box-" + boxNumber).prop(
'checked',
localStorage.getItem("checked" + boxNumber)
);
$("#box-" + boxNumber).click( function() {
localStorage.setItem(
"checked" + boxNumber,
$("#box-" + boxNumber).is(":checked")
);
});
})
}
$(document).ready(onReady);
Your check variable is getting overwritten, you can put it inside for loop.
So your code becomes,
function onClickBox() {
for(var i=1;i<=3;i++){
let checked=$("#box-"+i).is(":checked");
localStorage.setItem("checked-"+i, checked);
}
}
function onReady() {
for(var i=1;i<=3;i++){
if(localStorage.getItem("checked-"+i)=="true"){
var checked=true;
}
else{
var checked=false;
}
$("#box-"+i).prop('checked', checked);
onClickBox();
}
}
$(document).ready(onReady);
Please follow the below Code (Very Simple Javascript works)
<input type="checkbox" id="box">checkbox</input>
<button type="button" onClick="save()">save</button>
<script>
function save() {
var checkbox = document.getElementById("box");
localStorage.setItem("box", checkbox.checked);
}
//for loading...
var checked = JSON.parse(localStorage.getItem("box"));
document.getElementById("box").checked = checked;
</script>
with simple modification, you can use it without save button..
Hope this Helps you..

How do I keep single checkbox stay checked after refreshing the page?

HTML code:
<div class="wrap">
<h3>Background Swap:</h3>
<form action="" method="POST">
<div id="checkbox-container">
Shadowless background: <input type="checkbox" name="new_background" id="checker" <?php echo (isset($_POST['new_background']))? "checked='checked'": "";?>/><br /><br />
</div>
<input type="submit" name="submit" value="Upgrade Background" class="button" />
</form>
</div>
This will make the checkbox stays checked, but when page is refresh or exit and comes back, the checkbox will be unchecked. Therefore, after some research, I tried the localStorage, but doesn't seem to quite figure it out yet.
localStorage code:
var checkboxValue = JSON.parse(localStorage.getItem('checkboxValue')) || {};
var $checkbox = $("#checkbox-container :checkbox");
$checkbox.on("change", function(){
$checkbox.each(function(){
checkboxValue[this.id] = this.checked;
});
localStorage.setItem("checkboxValue", JSON.stringify(checkboxValue));
});
//on page load
$.each(checkboxValue, function(key, value){
$("#" + key).prop('checked', value);
});
I have script tags around the localStorage code and after implementing these codes, my checkbox still doesn't stays checked.
Both code as a whole:
<div class="wrap">
<h3>Background Swap:</h3>
<form action="" method="POST">
<div id="checkbox-container">
Background Swap: <input type="checkbox" name="new_background"/>
</div>
<script>
var checkboxValue = JSON.parse(localStorage.getItem('checkboxValue')) || {}
var $checkbox = $("#checkbox-container :checkbox");
$checkbox.on("change", function(){
$checkbox.each(function(){
checkboxValue[this.id] = this.checked;
});
localStorage.setItem("checkboxValue", JSON.stringify(checkboxValue));
});
//on page load
$.each(checkboxValue, function(key, value){
$("#" + key).prop('checked', value);
});
</script>
<input type="submit" name="submit" value="Upgrade Background" class="button"/>
</form>
</div>
I would like to thank everyone that took time to help me figure out the solution to my question with the biggest thanks to #Pranav C Balan!!! Check out the finished code # http://stackoverflow.com/a/44321072/3037257
I think your code is executing before the form elements are loading, so place it at the end of your code or wrap it using document ready handler to execute only after the elements are loaded. If you were placed the code before the element $("#checkbox-container :checkbox") would select nothing since it is not yet loaded in the DOM.
One more thing to do, in your code the checkbox doesn't have any id so add a unique id to the element to make it work since the JSON is generating using the id value.
<div class="wrap">
<h3>Background Swap:</h3>
<form action="" method="POST">
<div id="checkbox-container">
Background Swap: <input type="checkbox" id="name" name="new_background" />
</div>
<input type="submit" name="submit" value="Upgrade Background" class="button" />
</form>
<script>
var checkboxValue = JSON.parse(localStorage.getItem('checkboxValue')) || {}
var $checkbox = $("#checkbox-container :checkbox");
$checkbox.on("change", function() {
$checkbox.each(function() {
checkboxValue[this.id] = this.checked;
});
localStorage.setItem("checkboxValue", JSON.stringify(checkboxValue));
});
//on page load
$.each(checkboxValue, function(key, value) {
$("#" + key).prop('checked', value);
});
</script>
</div>
Working demo : FIDDLE
<script>
// document ready handler
// or $(document).ready(Function(){...
jQuery(function($) {
var checkboxValue = JSON.parse(localStorage.getItem('checkboxValue')) || {}
var $checkbox = $("#checkbox-container :checkbox");
$checkbox.on("change", function() {
$checkbox.each(function() {
checkboxValue[this.id] = this.checked;
});
localStorage.setItem("checkboxValue", JSON.stringify(checkboxValue));
});
//on page load
$.each(checkboxValue, function(key, value) {
$("#" + key).prop('checked', value);
});
});
</script>
<div class="wrap">
<h3>Background Swap:</h3>
<form action="" method="POST">
<div id="checkbox-container">
Background Swap: <input type="checkbox" id="name" name="new_background" />
</div>
<input type="submit" name="submit" value="Upgrade Background" class="button" />
</form>
</div>
Working demo : FIDDLE
An alternative to localStorage that only utilizes document.cookie:
$('input:checkbox').change(function() {
saveCookies();
});
To register the function and the actual function:
function saveCookies() {
var checkArray = [];
$('input.comic-check').each(function() {
if ($(this).is(':checked')) {
checkArray.push(1);
} else {
checkArray.push(0);
}
});
document.cookie = "checks=" + checkArray;
}
This is an alternative to localStorage, and depends on whether you want it to persist longer
And to retrieve the saved (on load)
var checks = getCookie("checks");
if (checks != "") {
checkArray = checks.split(',');
//unchecks boxes based on cookies
//also has backwards compatability provided we only append to the list in landing.ejs/generator.js
for (var i = 0; i < checkArray.length; i++) {
if (checkArray[i] == "0" && $('input.comic-check').length > i) {
var checkBox = $('input.comic-check')[i];
$(checkBox).prop('checked', false);
}
}
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
Three situations you will need to check the checkbox
PHP have it set to checked="checked" (checked)
localStorage have it as true (checked)
all other situations this should be unchecked
all you need is to make sure first two situation you check the checkbox, then by default it is unchecked, but in your each you are also uncheck checkbox, therefore ignored the PHP part (as php set it to checked but localStorege set it to unchecked)
Example here: https://jsfiddle.net/dalinhuang/efwc7ejb/
//on page load
$.each(checkboxValue, function(key, value) {
if(value){
$("#" + key).prop('checked', value);
}
});
I would change:
<?php echo (isset($_POST['new_background']))? "checked='checked'": "";?>
for:
<?php echo (isset($_POST['new_background']) && $_POST['new_background']=="on")? "checked" : "";?>
In inline HTML, you don't need the checked attribute to be checked=checked.
Just checked is enought.
checked=checked is used in JavaScript to programatically check a checkbox.
EDIT
About your localStorage...
I made an example for you on CodePen
//on page load, check the appropriate checkboxes.
var onloadChecks = JSON.parse(localStorage.getItem("checkboxValue"))
$.each(onloadChecks, function(key, value){
$("#" + key).prop('checked', value);
});
// ================ Saving checks
// Checkboxes collection.
var allCheckboxes = $("input[type='checkbox']");
// On change handler.
allCheckboxes.on("change", function() {
// Check how many checkboxes we have.
var jsonCheckboxes = {};
console.log("There is "+allCheckboxes.length+" checkboxes.");
// Building the json.
for(i=0;i<allCheckboxes.length;i++){
console.log(allCheckboxes.eq(i).attr("id"));
console.log(allCheckboxes.eq(i).is(":checked"));
jsonCheckboxes[allCheckboxes.eq(i).attr("id")] = allCheckboxes.eq(i).is(":checked");
}
console.log("jsonCheckboxes: "+JSON.stringify(jsonCheckboxes));
// Setting localStorage.
localStorage.setItem("checkboxValue", JSON.stringify(jsonCheckboxes));
console.log("LocalStorage: "+ localStorage.getItem("checkboxValue") );
});
Working around your comment : my goal is to find something that will make my checkbox stays checked if the user choose to, here's a way to have the localStorage handle it :
jQuery (3.2.1)
$(document).ready(function() {
var bground = localStorage.getItem('background'); // get the value if exists
if (bground == 'shadow') { // checkbox has been previously checked
$('#checker').attr('checked', 'checked');
}
if (bground == 'shadowless') { // checkbox has been previously unchecked
$('#checker').attr('');
}
$('#submit').submit(function() { // when form is submitted
bground = localStorage.getItem('background'); // get the value in LS
if($('#checker').is(':checked')) // is it checked or not ?
{ sh = 'shadow'; } else { sh = 'shadowless'; }
localStorage.setItem('background', sh); // update LS with new value
});
});
HTML (added id="submit" to form)
<form action="" id="submit" method="POST">
<div id="checkbox-container">
Shadowless background: <input type="checkbox" name="new_background" id="checker" /><br />
</div>
<input type="submit" name="submit" value="Upgrade Background" class="button" />
</form>
This will make the checkbox stays checked, and when page is refreshed, the checkbox will be checked/unchecked depending on user's previous choice.
You could also use the jQuery change function instead of form submitting.
Just modify the line :
$('#submit').submit(function() { // comment/delete this line
// to the one below
// $('#checker').change(function() { // uncomment this line

validate a field's value is greater than another field's value in php and javascript

I am working with form validations.
I have two text fields for adding budget. I want to check whether the value of total budget field is greater than that of daily budget in the click event of my submit button .I am using a form validation jquery plugin for validating my form. I want to customize that jquery with greaterthan rule.How can I validate a field's value is greater than another field's value in php and javascript..
I have tried with a method for greaterthan
Javascript:
method:
greaterThan: function(value, element, param)
{
var target = $(param);
return value <= target.val();
}
and
rules: {
totalbudget: {
required: true,
greaterThan:"#daylybudget"
},
But this is not working! How can I accomplish this?
var val1 = $('#textboxid1').val();
var val2 = $('#textboxid2').val();
var val3 = $('#textboxid3').val();
$('#submitbutton').click(function(){
if((val1 > val2) && (val2 > val3))
{
//prceed further
}
else
{
alert('alert message');
}
});
NOTE: You need to include jquery before this code..
First, javascript is client side, php is server side. Depending on the type of validation you need you can implement one of these validations or even both of them.
Considering the following form
<form method="post">
<input type="text" name="first_num" id="first_num" />
<input type="text" name="second_num" id="second_num" />
<input type="text" name="third_num" id="third_num" />
<input type="submit" value="Send & validate" onclick="validate()" />
</form>
Here's a javascript way of doing it:
<script type="text/javascript">
function validate()
{
var value1;
var value2;
var value3;
value1 = parseFloat(document.getElementById('first_num').value);
value2 = parseFloat(document.getElementById('second_num').value);
value3 = parseFloat(document.getElementById('third_num').value);
if (value1 > value2 && value2 > value3)
{
//we're ok
}
else
{
alert("Values are not as they should be");
return false;
}
}
</script>
As for the php side:
<?php
$value1 = $_POST['first_num'];
$value2 = $_POST['second_num'];
$value3 = $_POST['third_num'];
if ($value1 > $value2 && $value2 > $value3)
{
//do whatever you want because the values are as you wish
}
else
{
//the values are not as they should be
}
?>
Keep in mind that usually, for this kind of validation, javascript might be just enough.

Unable to check if a javascript checkbox array element is checked or not?

What is want is - when the checkbox is checked option no. 5 in select list will be selected and when the checkbox is unchecked option no. 0 will be selected in the select list.
The select list and the checkboxes are generated dynamically in the php code as below :
echo "<select name='coupons".$i."' id='coupons".$i."'>";
------- All Options --------
echo "</select>";
<input type='checkbox' name='myCheckbox[]' value='<?php echo $i."_".$row->id; ?>' onclick='setCCode("myCheckbox[]",<?php echo $i;?>)'>
-----------------------------------------------------------------------------
Solved the second requirement on my own now ..... thanks to all for your inputs
just added the following line in the checkAll() within the for loop
setCCode(children[i],i+1);
The javascript function :
function setCCode(checkbox_name,i)
{
var form_object = document.getElementsByName(checkbox_name+"["+i+"]");
var selname = document.getElementsByName("coupons"+i)[0];
if(form_object.checked) {
selname.selectedIndex = 5;
}
else {
selname.selectedIndex = 0;
}
}
The above issue is solved....... thanks to all
Now what i need to do is when a user checks a checkbox to select or deselect all the dynamically generated checkboxes on the form the above logic should work.
<input type='checkbox' name='checkall' onChange="checkAll(this, 'myCheckbox[]')">
<span class="chkall">Check / Uncheck All</span>
<input type='checkbox' name='myCheckbox[]' value='<?php echo $i."_".$row->id; ?>' onclick='setCCode(this,<?php echo $i;?>)'>
The javascript code i am using to select/deselect all checkboxes on form is as below :
function checkAll(parent, field)
{
var children = document.getElementsByName(field);
var newValue = parent.checked;
for (i = 0; i < children.length; i++){
if (children[i].disabled == false) {
children[i].checked = newValue;
}
}
}
function setCCode(Sender,i)
{
document.getElementsByName("coupons"+i)[0].selectedIndex = Sender.checked ? 5 : 0;
}
getElementsByName returns an array of objects. Replace the line with:
var form_object = document.getElementsByName(checkbox_name+"["+i+"]")[0];
You can pass refference to the checkbox itself as a parameter
<input type='checkbox' name='myCheckbox[]' value='<?php echo $i."_".$row->id; ?>' onclick='setCCode(this,<?php echo $i;?>)'>
function setCCode(Sender,i)
{
document.getElementsByName("coupons"+i)[0].selectedIndex = Sender.checked ? 5 : 0;
}
If you have a reference to the form that the checkbox is in, and it has a unique name in the form, then you can access it as:
form_object = form.elements[ checkbox_name + "[" + i + "]" ];
and you can also use the ternary operator to make the code more concise:
selname.selectedIndex = form_object.checked? 5 : 0;
Edit
Sorry, missed the obvious. If you pass a refereference to the checkbox in the handler, then you can also get the form (all form controls have a form property that references the form they are in). So as Jan Pfeifer suggested (abbreviated markup):
<input ... onclick='setCCode(this, <?php echo $i;?>)'>
then the script is just:
function setCCode(checkbox, i)
{
checkbox.form.elements['coupons' + i].selectedIndex = checkbox.checked? 5 : 0;
}

Categories

Resources