clicking through saved checkbox states - javascript

The below works to save the states of my checkboxes, then sets the items saved back to checked when called in my load__() function; however I need to instead of just setting to checked, I need to actually have them .click() through in my load__() function as the data is not being served otherwise.
function checkSaver() {
user = JSON.parse(localStorage.getItem(user));
var inputs = document.querySelectorAll('input[type="checkbox"]');
user.userAchkData = [];
inputs.forEach(function(input){
user.userAchkData.push({ id: input.id, checked: input.checked });
});
localStorage.setItem(username, JSON.stringify(user));
console.log(JSON.stringify(user));
}
function load_() {
// get saved latest checkbox states, recheck
user = JSON.parse(localStorage.getItem(user));
var inputs = user.userAchkData;
inputs.forEach(function(input){
if (input.id) {
// I need to click through the found checked here
document.getElementById(input.id).checked = input.checked;
}
});

You can check if they're checked and then programmatically trigger a click:
if (input.id) {
// I need to click through the found checked here
const element = document.getElementById(input.id);
element.checked = input.checked;
if (input.checked) element.click();
}
I fiddled around a bit and got to a simple working example for checking saved checkboxes. Maybe you can adapt this to your needs:
const container = document.getElementById('checkboxes');
const data = JSON.parse(localStorage.getItem('checkboxes')) || new Array(3).fill(false);
window.addEventListener('DOMContentLoaded', () => {
[...container.children].forEach((child, i) => { child.checked = data[i]; });
});
container.onchange = ({ target }) => {
data[target.dataset.id] = target.checked;
localStorage.setItem('checkboxes', JSON.stringify(data));
};
<div id="checkboxes">
<input type="checkbox" data-id="0">
<input type="checkbox" data-id="1">
<input type="checkbox" data-id="2">
</div>

Related

Change radio button based on other radio button's value

How do I deal with this behaviour:
Relevant HTML:
<p>
Player 1: <input type="text" name="player1Name">
<input type="radio" name="option1" value="X" id='option1X'/> X
<input type="radio" name="option1" value="O" id='option1O' /> O
</p>
<p>
Player 2: <input type="text" name="player2Name">
<input type="radio" name="option2" value="X" id='option2X' /> X
<input type="radio" name="option2" value="O" id='option2O'/> O
</p>
Here's what I have tried:
const option2X = document.getElementById('option2X');
const option2O = document.getElementById('option2O');
const option1X = document.getElementById('option1X');
const option1O = document.getElementById('option1O');
function checkRadios(option1, option2, option3) {
option1.addEventListener('click', function () {
if(option1.checked && option2.checked)
option3.setAttribute('checked', 'true');
});
}
checkRadios(option1X, option2X, option2O);
checkRadios(option1O, option2O, option2X);
checkRadios(option2X, option1X, option1O);
checkRadios(option2O, option1O, option1X);
This works for the first time and then it stops working.
I checked the debugger, and the reason is that option3's value changes somehow.
Player1's radios are option1X and option1O.
What I want:
If an option is clicked by user A and the same option has already been taken by another user (B), then the other user's (B's) radio should change.
I tried changing the 'click' event to 'change' and that also didn't work.
Is this what you want?
I have used addEventListener method for calling a function that checks another radio button. There exists no need for clearing selected checkbox. This is because as soon as you check one radio button out of the two, other automatically gets deselected.
I have also used a function to check if both the two options are selected or not. If they are not, null is returned and then nothing happens. But if both of them are selected, manipulation of selected radio button takes place.
const option2X = document.getElementById('option2X');
const option2O = document.getElementById('option2O');
const option1X = document.getElementById('option1X');
const option1O = document.getElementById('option1O');
check = () => document.querySelector('input[name="option1"]:checked') && document.querySelector('input[name="option2"]:checked');
option1X.addEventListener("change", function() {if (check()) option2O.checked = true});
option2X.addEventListener("change", function() {if (check()) option1O.checked = true});
option1O.addEventListener("change", function() {if (check()) option2X.checked = true});
option2O.addEventListener("change", function() {if (check()) option1X.checked = true});
Note: This starts working from MS Edge 12. For lower versions, change the check function to
function check() {
return document.querySelector('input[name="option1"]:checked') && document.querySelector('input[name="option2"]:checked');
}
You may simply allow only the first player to choose the letter.
Anyway, you can simply change the checked property of the radio buttons:
switch (player1.choice) {
case "X":
player2RadioX.checked = false;
player2RadioX.enabled = false;
player2RadioO.checked = true;
player2RadioO.enabled = true;
break;
case "O":
player2RadioO.checked = false;
player2RadioO.enabled = false;
player2RadioX.checked = true;
player2RadioX.enabled = true;
break;
}

submit button get checkbox input safed in object jquery

I'm new to jquery and I have a question about how i can save the input from my checkboxes in an object when clicking on a button.
For now i just want it to see it in the console.
my code looks something like this:
let UserInput = [];
const addUserInput = (ev) => {
ev.preventDefault();
let TextInput = {
Name: document.getElementById('exampleInputName').value, //this is working
InfoElektronik: $('#Info-Elektronik').click(function() { //this is not?
console.log("Checkbox1 = " + $('#Info-Elektronik').prop('checked'));
});
};
};
<div class="form-check">
<input class="form-check-input" type="checkbox" name="agree" value="" id="Info-Elektronik">
<label class="form-check-label" for="defaultCheck1">Elektronik</label>
</div>
The issue is that InfoElektronik stores a function, not the actual return value.
Also in your click function, you log the value to the console.
I would do it like this:
const TextInput = {
Name: document.getElementById('exampleInputName').value
}
$('#Info-Elektronik').click(function() {
textInput.InfoElektronik = ("Checkbox1 = " + $('#Info-Elektronik').prop('checked')).val();
})

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..

Javascript validation - group validation - if one entered, then all required

Using just jQuery (not validation plugin) I have devised a way to do a "if one, then all" requirement, but it's not at all elegant.
I'm wondering if someone can come up with a more elegant solution? This one uses some loop nesting and I'm really not pleased with it.
if ($("[data-group]")) {
//Store a simple array of objects, each representing one group.
var groups = [];
$("[data-group]").each(function () {
//This function removes an '*' that is placed before the field to validate
removeCurError($(this));
var groupName = $(this).attr('data-group');
//If this group is already in the array, don't add it again
var exists = false;
groups.forEach(function (group) {
if (group.name === groupName)
exists = true;
});
if (!exists) {
var groupElements = $("[data-group='" + groupName + "']");
var group = {
name: groupName,
elements: groupElements,
trigger: false
}
group.elements.each(function () {
if (!group.trigger) {
group.trigger = $(this).val().length !== 0;
}
});
groups.push(group);
}
});
//Now apply the validation and alert the user
groups.forEach(function (group) {
if (group.trigger) {
group.elements.each(function () {
//Make sure it's not the one that's already been filled out
if ($(this).val().length === 0)
// This function adds an '*' to field and puts it into a
// a sting that can be alerted
appendError($(this));
});
}
});
You don't have to store the groups in an array, just call the validateGroups function whenever you want to validate the $elements. Here is a working example http://jsfiddle.net/BBcvk/2/.
HTML
<h2>Group 1</h2>
<div>
<input data-group="group-1" />
</div>
<div>
<input data-group="group-1" />
</div>
<h2>Group 2</h2>
<div>
<input data-group="group-2" value="not empty" />
</div>
<div>
<input data-group="group-2" />
</div>
<div>
<input data-group="group-2" />
</div>
<button>Validate</button>
Javascript
function validateGroups($elements) {
$elements.removeClass('validated');
$elements.each(function() {
// Return if the current element has already been validated.
var $element = $(this);
if ($element.hasClass('validated')) {
return;
}
// Get all elements in the same group.
var groupName = $element.attr('data-group');
var $groupElements = $('[data-group=' + groupName + ']');
var hasOne = false;
// Check to see if any of the elements in the group is not empty.
$groupElements.each(function() {
if ($(this).val().length > 0) {
hasOne = true;
return false;
}
});
// Add an error to each empty element if the group
// has a non-empty element, otherwise remove the error.
$groupElements.each(function() {
var $groupElement = $(this);
if (hasOne && $groupElement.val().length < 1) {
appendError($groupElement);
} else {
removeCurError($groupElement);
}
$groupElement.addClass('validated');
});
});
}
function appendError($element) {
if ($element.next('span.error').length > 0) {
return;
}
$element.after('<span class="error">*</span>');
}
function removeCurError($element) {
$element.next().remove();
}
$(document).ready(function() {
$('button').on('click', function() {
validateGroups($("[data-group]"));
});
});
You might get some milage out of this solution. Basically, simplify and test your solution on submit click before sending the form (which this doesn't do). In this case, I simply test value of the first checkbox for truth, and then alert or check the required boxes. These can be anything you like. Good luck.
http://jsfiddle.net/YD6nW/1/
<form>
<input type="button" onclick="return checkTest()" value="test"/>
</form>
and with jquery:
checkTest = function(){
var isChecked = $('input')[0].checked;
if(isChecked){
alert('form is ready: input 0 is: '+isChecked);
}else{
$('input')[1].checked = true;
$('input')[2].checked = true;
}
};
//create a bunch of checkboxes
$('<input/>', {
type: 'checkbox',
html: 'tick'
}).prependTo('form');
$('<input/>', {
type: 'checkbox',
html: 'tick'
}).prependTo('form');
$('<input/>', {
type: 'checkbox',
html: 'tick'
}).prependTo('form');

Select all radio buttons which are checked with prototype

I have several input elements which look like this:
<input type="radio" checked="checked" value="1" name="handle[123]" />
<input type="radio" checked="checked" value="2" name="handle[456]" />
The number inside the name attribute is an object id i need. Now what I want to do is:
Fetch all input which are of type="radio" and are checked with prototype
Put all ids and values in an associative array
...so the resulting array looks something like this:
array{ 1 => 123, 2 => 456 }
Any ideas?
Here's what I came up with:
var results = [];
document.body.select('input[type=radio]:checked').each(function (element) {
var object = {};
object[element.value] = element.name.match(/\d+/)[0];
results.push(object);
});
new Ajax.Request('/some_url', {
method: 'post',
parameters: results
});
Demo
To get the checked radio button given a form id, and the name of the radio group:
function RF(el, radioGroup) {
if($(el).type && $(el).type.toLowerCase() == 'radio') {
var radioGroup = $(el).name;
var el = $(el).form;
} else if ($(el).tagName.toLowerCase() != 'form') {
return false;
}
var checked = $(el).getInputs('radio', radioGroup).find(
function(re) {return re.checked;}
);
return (checked) ? $F(checked) : null;
}
var value = RF('form_id', 'radio_grp_name');
Hope it helps
$$('input:checked[type=radio]').each(function (ele) {
output[ele.name.match(/\d+/)[0]] = ele.value;
});
This would give the desired output using prototype

Categories

Resources