Save multipule checkboxs individual states after page refresh - javascript

I have 15 or so individual checkboxes each without id or class, the problem is I would like for them all to retain their individual checked or unchecked status (using local storage) either on form submit or page refresh
<form name="searchform" id="form1" method="get" action="/ztest.php">
<input type="checkbox" name="opt17" value="Yes"/>
<input type="checkbox" name="opt18" value="Yes"/>
<input type="checkbox" name="opt19" value="Yes"/>
etc...
</form>
My question is, is this possible in Javascript to save them in local storage without having to assign a class or id to each checkbox?
If possible, a working fiddle would be gratefully appreciated
Jason

Let's assume our checkboxes are blind
<input type="checkbox" onclick = "clickThis(event)" value="Yes"/>
<input type="checkbox" onclick = "clickThis(event)" value="Yes"/>
<input type="checkbox" onclick = "clickThis(event)" value="Yes"/>
<input type="checkbox" onclick = "clickThis(event)" value="Yes"/>
<input type="checkbox" onclick = "clickThis(event)" value="Yes"/>
<input type="checkbox" onclick = "clickThis(event)" value="Yes"/>
Now we need to find out which element was clicked, for this we can get the index of the element which is clicked.
const clickedIndex = [...event.target.parentElement.children].indexOf(event.target);
this line will gives you the index of clicked element which you can save in your localstorage
localStorage.setItem([...el.parentElement.children].indexOf(el), [...el.parentElement.children].indexOf(el));
and also you can check whenever your page load that which index is saved in your localstorage.
const inputs = document.querySelectorAll("input");
console.log(inputs);
if (localStorage.length > 0) {
for (let key in localStorage) {
if (!isNaN(localStorage[key]))
inputs[localStorage[key]].checked = true;
}
}
hence the complete code
<body>
<input type = "checkbox" onclick = "clickThis(event)"/>
<input type = "checkbox" onclick = "clickThis(event)"/>
<input type = "checkbox" onclick = "clickThis(event)"/>
<input type = "checkbox" onclick = "clickThis(event)"/>
<input type = "checkbox" onclick = "clickThis(event)"/>
<input type = "checkbox" onclick = "clickThis(event)"/>
<input type = "checkbox" onclick = "clickThis(event)"/>
<input type = "checkbox" onclick = "clickThis(event)"/>
</body>
<script>
const inputs = document.querySelectorAll("input");
console.log(inputs);
if (localStorage.length > 0) {
for (let key in localStorage) {
if (!isNaN(localStorage[key]))
inputs[localStorage[key]].checked = true;
}
}
function clickThis(event) {
console.log(event.target);
const el = event.target;
const clickedIndex = [...el.parentElement.children].indexOf(el);
if (event.target.checked) {
// adding click value to local storage
localStorage.setItem([...el.parentElement.children].indexOf(el), [...el.parentElement.children].indexOf(el));
} else {
// deleting unchecked value from localstorage
localStorage.removeItem([...el.parentElement.children].indexOf(el), [...el.parentElement.children].indexOf(el));
}
}
</script>
#happy_coding
REPL link
https://repl.it/repls/SlateblueCorruptScale

This is the second way to achieve the above problem.
Let's assume you don't want to define that onclick on each of your tag.
all you need to do is listen the event. shhhhh
document.addEventListener("click", function(event){
console.log(event.target);
});
so you are able to listen the event right ?. Now where in your body you click will be heard by this. But as per your scenario you need to listen only when the input type checkbox clicked.
so we will add a condition
if (event.target.type === "checkbox") {
// this is checkbox bro
}
and rest of strategy will be same like get the index store it into local-storage and add the checkbox value true while loading.
so here is complete code
<body>
<input type = "checkbox"/>
<input type = "checkbox" />
<input type = "checkbox"/>
<input type = "checkbox"/>
<input type = "checkbox"/>
<input type = "checkbox"/>
<input type = "checkbox"/>
<input type = "checkbox"/>
</body>
<script>
const inputs = document.querySelectorAll("input");
console.log(inputs);
if (localStorage.length > 0) {
for (let key in localStorage) {
if (!isNaN(localStorage[key]))
inputs[localStorage[key]].checked = true;
}
}
document.addEventListener("click", function(event){
console.log(event.target);
if (event.target.type === "checkbox") {
const el = event.target;
const clickedIndex = [...el.parentElement.children].indexOf(el);
if (event.target.checked) {
// adding click value to local storage
localStorage.setItem([...el.parentElement.children].indexOf(el), [...el.parentElement.children].indexOf(el));
} else {
// deleting unchecked value from localstorage
localStorage.removeItem([...el.parentElement.children].indexOf(el), [...el.parentElement.children].indexOf(el));
}
}
});
</script>
REPLLINK

Related

How to set radio button value as checked or unchecked situation

<input type="radio" name="imgsel" value="" checked />
My requirement is : This radio button by default checked then value of this button is 'present'. When this button is unchecked , then value this button is 'absent'.
how can i do this?
please, help me .
Thanks in advance .
function valChange(element)
{
if (element.checked)
{
alert("present");
} else
{
alert("absent");
}
}
<input id="button" type="checkbox" name="imgsel"
onchange="valChange(this)" value="" checked />
The following example replaces the value of the checkbox when clicked.
First the click event must be bound to the checkbox. The EventHandler checks whether the box has already been checked. If not, it checks it and sets the value in the checkbox. And if it has not been checked, the other way round.
let i = document.querySelector('input');
i.addEventListener('click', (ev) => {
let el = ev.target;
if (el.getAttribute('checked') === null) {
el.setAttribute('checked', true);
el.value = "present"
} else {
el.removeAttribute('checked');
el.value = "absent"
}
let checkValue = document.querySelector('input').value
alert(checkValue)
})
<input type="radio" name="imgsel" value="" checked />

Removing value from array according to index using splice()

I have 4 checkboxes. I add values of them to an array on check. It looks like this.
Here are the four checkboxes I have.
<input type="checkbox" value="degree">
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
Once I check all four of them, the array becomes,
["degree", "pgd", "hnd", "advdip"]
When I uncheck a checkbox, I need to remove the value of it from the array according to its correct index number. I used splice() but it always removes the first index which is degree. I need to remove the value from the array according to its index number no matter which checkbox I unselect. Hope someone helps. Below is the code. Thanks in advance!
<input type="checkbox" value="degree">
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
<script>
function getLevels() {
// get reference to container div of checkboxes
var con = document.getElementById('course-levels');
// get reference to input elements in course-levels container
var inp = document.getElementsByTagName('input');
// create array to hold checkbox values
var selectedValues = [];
// collect each input value on click
for (var i = 0; i < inp.length; i++) {
// if input is checkbox
if (inp[i].type === 'checkbox') {
// on each checkbox click
inp[i].onclick = function() {
if ($(this).prop("checked") == true) {
selectedValues.push(this.value);
console.log(selectedValues);
}
else if ($(this).prop("checked") == false) {
// get index number
var index = $(this).index();
selectedValues.splice(index, 1);
console.log(selectedValues);
}
}
}
}
}
getLevels();
</script>
You used the wrong way to find index in your code. If you used element index, it will avoid real index in your array and gives the wrong output. Check below code, it may be work for you requirement.
<input type="checkbox" value="degree">
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
<script src="https://code.jquery.com/jquery-3.5.0.min.js" integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=" crossorigin="anonymous"></script>
<script>
function getLevels() {
// get reference to container div of checkboxes
var con = document.getElementById('course-levels');
// get reference to input elements in course-levels container
var inp = document.getElementsByTagName('input');
// create array to hold checkbox values
var selectedValues = [];
// collect each input value on click
for (var i = 0; i < inp.length; i++) {
// if input is checkbox
if (inp[i].type === 'checkbox') {
// on each checkbox click
inp[i].onclick = function() {
if ($(this).prop("checked") == true) {
selectedValues.push(this.value);
console.log(selectedValues);
}
else if ($(this).prop("checked") == false) {
// get index number
var index = selectedValues.indexOf(this.value);
selectedValues.splice(index, 1);
console.log(selectedValues);
}
}
}
}
}
getLevels();
</script>
Add change handler to the inputs and use jQuery map to get the values of the checked inputs.
var levels
$('#checkArray input').on('change', function () {
levels = $('#checkArray input:checked').map(function () {
return this.value
}).get()
console.log(levels)
}).eq(0).change()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset id="checkArray">
<input type="checkbox" value="degree" checked>
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
</fieldset>
my approach was to add an event handler that reads all checked values when any of those inputs is clicked and empty the array before loging the response. no need to add any dependencies with this one
Hope this is what you are looking for
function getLevels() {
let checkboxContainer = document.getElementById("checkboxContainer");
let inputs = checkboxContainer.querySelectorAll("input");
let checked = [];
inputs.forEach( (input) => {
checked = [];
input.addEventListener( 'click', () => {
checked = [];
inputs.forEach( (e) => {
e.checked ? checked.push(e.value) : null;
})
console.log(checked);
});
});
}
getLevels();
<div id="checkboxContainer">
<input type="checkbox" value="degree" >
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
</div>
I don't know if this is what you need, to show an array of the selected values, if you want you can call the function that calculates on the check.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<fieldset id="checkArray">
<input type="checkbox" value="degree" checked>
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
</fieldset>
<button onclick="getLevels()">getLevels</button>
<script>
function getLevels() {
var levels = [];
$.each($("input:checked"), function() {
levels.push(($(this).val()));
});
console.log(levels);
}
getLevels();
</script>

Validation with input[type="radio"] return always false

I have an input[type="radio"], with no checked option by default, and i need to return false if none of these options are checked.
I'm exploring javascript only, so a jquery, angular or any other will be useles (at this moment).
I'm able to iterate over a radioObj and select its value, but i can't return false if no option is checked (actually, i can't return true)
not exactly what i have, but...
<input type="radio" id="rd1" name="radioGrp">opt1
<br>
<input type="radio" id="rd2" name="radioGrp">opt2
and in JS i have...
var rdObj = document.getElementByName("radioGrp");
var selectedValue;
for (var i = 0, length = rdObj.length; i < length; i++){
if(!rdObj[i].checked){
alert("Select one option");
return false;
}else{
//do something with value of radio checked value
}
}
This code always gives me the alert("Select one option"), no matter if i select one option or not.
Need for validation.
Any hel will be very appreciated
You probably want to wait for an event before you do any sort of value checking, otherwise your script will only run once, and at this point in time, nothing would have ever had the chance be checked.
You can attach a change event listener to each of your radios...
var myRadios = document.querySelectorAll('[name=radioGrp]');
var selectedValue;
myRadios.forEach(radio => {
radio.addEventListener('change', changeHandler);
})
function changeHandler(evt) {
// do some check in here
console.log(evt.target.value)
}
<input type="radio" id="rd1" name="radioGrp" value='opt1'>opt1
<br>
<input type="radio" id="rd2" name="radioGrp" value='opt2'>opt2
...or you can attach a submit event handler to your form and do some checking of your data then.
const myForm = document.querySelector('form');
myForm.addEventListener('submit', submitHandler);
function submitHandler(evt) {
evt.preventDefault();
const data = new FormData(evt.target);
const optionVal = data.get('radioGrp');
// do some check in here
if (!optionVal) {
console.log(`Please select a value`)
} else {
console.log(`Thanks for selecting ${optionVal}`)
}
}
<form>
<input type="radio" id="rd1" name="radioGrp" value='opt1'>opt1
<br>
<input type="radio" id="rd2" name="radioGrp" value='opt2'>opt2
<input type="submit">
</form>
You can try this:
function validateForm() {
var radios = document.getElementsByName("radioGrp");
var formValid = false;
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
formValid = true;
break;
}
}
if (!formValid) {
alert("Select one option");
}
return formValid;
}
<form name="form1" action="#" onsubmit="return validateForm();" method="post">
<input type="radio" id="rd1" name="radioGrp">opt1
<br>
<input type="radio" id="rd2" name="radioGrp">opt2
<br>
<input type="submit" value="Submit">
</form>

Get value from textbox based on checkbox on change event

I have two textboxes and one checkbox in a form.
I need to create a function javascript function for copy the first txtbox value to second textbox on checkbox change event.
I use the following code but its shows null on first time checkbox true.
function ShiptoBill()
{
var billing = document.getElementById("txtbilling").value;
var shipping = document.getElementById("txtshipping").value;
var check = // here i got checkbox checked or not
if(check == true)
{
// here I need to add the txtbilling value to txtshipping
}
}
Given that form controls can be accessed as named properties of the form, you can get a reference to the form from the checkbox, then conditionally set the value of txtshipping to the value of txtbilling depending on whether it's checked or not, e.g.:
<form>
<input name="txtbilling" value="foo"><br>
<input name="txtshipping" readonly><br>
<input name="sameas" type="checkbox" onclick="
this.form.txtshipping.value = this.checked? this.form.txtbilling.value : '';
"><br>
<input type="reset">
</form>
Of course you might want to set the listener dynamically, the above just provides a hint. You could also conditionally copy the contents over if the user changes them and the checkbox is checked, so a change event listener on txtbilling may be required too.
Try like following.
function ShiptoBill() {
var billing = document.getElementById("txtbilling");
var shipping = document.getElementById("txtshipping");
var check = document.getElementById("checkboxId").checked;
if (check == true) {
shipping.value = billing.value;
} else {
shipping.value = '';
}
}
<input type="text" id="txtbilling" />
<input type="text" id="txtshipping" />
<input type="checkbox" onchange="ShiptoBill()" id="checkboxId" />
function ShiptoBill()
{
var billing = document.getElementById("txtbilling");
var shipping = document.getElementById("txtshipping");
var check = document.getElementById("checkboxId").checked; // replace 'checkboxId' with your checkbox 'id'
if (check == true)
{
shipping.value = billing.value;
}
}
To get the event when it changes, do
$('#checkbox1').on('change',function() {
if($(this).checked) {
$('#input2').val($('#input1').val());
}
});
This checks for the checkbox to have a change, then checks if it is checked. If it is, it places the value of Input Box 1 into the value of Input Box 2.
EDIT: Here's a pure JS solution, and a JSBin too.
function ShiptoBill()
{
var billing = document.getElementById("txtbilling").value;
var shipping = document.getElementById("txtshipping").value;
var check = document.getElementById("thischeck").checked;
console.log(check);
if(check == true)
{
console.log('checked');
document.getElementById("txtshipping").value = billing;
} else {
console.log('not checked');
}
}
with
<input id="thischeck" type="checkbox" onclick="ShiptoBill()">

Javascript checkbox onChange

I have a checkbox in a form and I'd like it to work according to following scenario:
if someone checks it, the value of a textfield (totalCost) should be set to 10.
then, if I go back and uncheck it, a function calculate() sets the value of totalCost according to other parameters in the form.
So basically, I need the part where, when I check the checkbox I do one thing and when I uncheck it, I do another.
Pure javascript:
const checkbox = document.getElementById('myCheckbox')
checkbox.addEventListener('change', (event) => {
if (event.currentTarget.checked) {
alert('checked');
} else {
alert('not checked');
}
})
My Checkbox: <input id="myCheckbox" type="checkbox" />
function calc()
{
if (document.getElementById('xxx').checked)
{
document.getElementById('totalCost').value = 10;
} else {
calculate();
}
}
HTML
<input type="checkbox" id="xxx" name="xxx" onclick="calc();"/>
If you are using jQuery.. then I can suggest the following:
NOTE: I made some assumption here
$('#my_checkbox').click(function(){
if($(this).is(':checked')){
$('input[name="totalCost"]').val(10);
} else {
calculate();
}
});
Use an onclick event, because every click on a checkbox actually changes it.
The following solution makes use of jquery. Let's assume you have a checkbox with id of checkboxId.
const checkbox = $("#checkboxId");
checkbox.change(function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
});
HTML:
<input type="checkbox" onchange="handleChange(event)">
JS:
function handleChange(e) {
const {checked} = e.target;
}
Reference the checkbox by it's id and not with the #
Assign the function to the onclick attribute rather than using the change attribute
var checkbox = $("save_" + fieldName);
checkbox.onclick = function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
};
Javascript
// on toggle method
// to check status of checkbox
function onToggle() {
// check if checkbox is checked
if (document.querySelector('#my-checkbox').checked) {
// if checked
console.log('checked');
} else {
// if unchecked
console.log('unchecked');
}
}
HTML
<input id="my-checkbox" type="checkbox" onclick="onToggle()">
try
totalCost.value = checkbox.checked ? 10 : calculate();
function change(checkbox) {
totalCost.value = checkbox.checked ? 10 : calculate();
}
function calculate() {
return other.value*2;
}
input { display: block}
Checkbox: <input type="checkbox" onclick="change(this)"/>
Total cost: <input id="totalCost" type="number" value=5 />
Other: <input id="other" type="number" value=7 />
I know this seems like noob answer but I'm putting it here so that it can help others in the future.
Suppose you are building a table with a foreach loop. And at the same time adding checkboxes at the end.
<!-- Begin Loop-->
<tr>
<td><?=$criteria?></td>
<td><?=$indicator?></td>
<td><?=$target?></td>
<td>
<div class="form-check">
<input type="checkbox" class="form-check-input" name="active" value="<?=$id?>" <?=$status?'checked':''?>>
<!-- mark as 'checked' if checkbox was selected on a previous save -->
</div>
</td>
</tr>
<!-- End of Loop -->
You place a button below the table with a hidden input:
<form method="post" action="/goalobj-review" id="goalobj">
<!-- we retrieve saved checkboxes & concatenate them into a string separated by commas.i.e. $saved_data = "1,2,3"; -->
<input type="hidden" name="result" id="selected" value="<?= $saved_data ?>>
<button type="submit" class="btn btn-info" form="goalobj">Submit Changes</button>
</form>
You can write your script like so:
<script type="text/javascript">
var checkboxes = document.getElementsByClassName('form-check-input');
var i;
var tid = setInterval(function () {
if (document.readyState !== "complete") {
return;
}
clearInterval(tid);
for(i=0;i<checkboxes.length;i++){
checkboxes[i].addEventListener('click',checkBoxValue);
}
},100);
function checkBoxValue(event) {
var selected = document.querySelector("input[id=selected]");
var result = 0;
if(this.checked) {
if(selected.value.length > 0) {
result = selected.value + "," + this.value;
document.querySelector("input[id=selected]").value = result;
} else {
result = this.value;
document.querySelector("input[id=selected]").value = result;
}
}
if(! this.checked) {
// trigger if unchecked. if checkbox is marked as 'checked' from a previous saved is deselected, this will also remove its corresponding value from our hidden input.
var compact = selected.value.split(","); // split string into array
var index = compact.indexOf(this.value); // return index of our selected checkbox
compact.splice(index,1); // removes 1 item at specified index
var newValue = compact.join(",") // returns a new string
document.querySelector("input[id=selected]").value = newValue;
}
}
</script>
The ids of your checkboxes will be submitted as a string "1,2" within the result variable. You can then break it up at the controller level however you want.

Categories