get value of checked checkbox list in array in jQuery - javascript

I have list of checkboxes that has all checkbox pre-checked when page load.
Firstly, I want to read all checkboxes (checked) value and store in global array.
Later, whenever any checkbox is clicked by user (un-checked / checked), I want to update the array with values of only checked checkboxes.
All this i want to do in jQuery.
thanks

<input type="checkbox" value="somevalue1" class="chk">
<input type="checkbox" value="somevalue2" class="chk">
<input type="checkbox" value="somevalue3" class="chk">
<input type="checkbox" value="somevalue4" class="chk">
<input type="checkbox" value="somevalue5" class="chk">
<script>
var someGlobalArray = new Array;
$(".chk").click(function() {
someGlobalArray=[];
$('.chk:checked').each(function() {
someGlobalArray.push($(this).val());
});
console.log(someGlobalArray);
});
</script>

Did you mean something like this?
var arrCheckboxes;
var checkboxSelector = "input[type='checkbox']";
$("body").delegate(checkboxSelector , "click", function(){
arrCheckboxes = $(checkboxSelector).map(function() {
return this.checked;
}).get();
});
(Maybe you should change the $("body") to a more precise container)
If you want an array with objects with name (...or id or maybe the element)... you can do something like this:
var arrCheckboxes;
var checkboxSelector = "input[type='checkbox']";
$("body").delegate(checkboxSelector , "change", function(){
arrCheckboxes = $(checkboxSelector).map(function() {
return { name: this.name, val: this.checked };
}).get();
});

I assume that you want is the name or id of the checked items, since checkbox values are boolean?
var checked = {};
$(':input[type="checkbox"]').each(function() {
var name= this.name;
var val = this.checked;
if (val) {
checked[name] = val;
}
}).on('change', function() {
var name = this.name;
var val = this.checked;
if (val) {
checked[name] = val;
} else {
delete checked[name];
}
});
The object checked will then contain keys, and only those corresponding to checked items will appear in that object.
Working demo at http://jsfiddle.net/tFYPF/

Related

How do you save multiple key value pairs to one cookie with JavaScript/jQuery?

I have a form with multiple checkboxes in it and when I click them, I want to add/remove the key-value pairs (name of the input + true/false) in one single cookie.
When I click on the checkboxes only the first pair gets shown in console.log.
This is what I ended up with so far:
HTML:
<form class="form">
<input class="input" name="expert_id_1" type="checkbox" />
<input class="input" name="expert_id_2" type="checkbox" />
<input class="input" name="expert_id_3" type="checkbox" />
<input class="input" name="expert_id_4" type="checkbox" />
</form>
JS:
function setCookie() {
var customObject = {};
var inputName = $('.input').attr('name');
customObject[inputName] = $('.input').prop('checked');
var jsonString = JSON.stringify(customObject);
document.cookie = 'cookieObject=' + jsonString;
console.log(jsonString);
}
function getCookie() {
var nameValueArray = document.cookie.split('=');
var customObject = JSON.parse(nameValueArray[1]);
$('.input').prop('checked') = customObject[inputName];
}
$('.input').each(function() {
$(this).on('click', function() {
if ($(this).is(':checked')) {
$(this).attr('value', 'true');
} else {
$(this).attr('value', 'false');
}
setCookie();
});
});
Your cookie is being overrided and it might only store the first checkbox info. Also to set the prop value, you have to pass it as a second parameter.
This should update the cookie when clicked and also be able to set the values from the cookie.
function updateCookie($input) {
var cookieObject = getCookieObject();
var inputName = $input.attr('name');
cookieObject[inputName] = $input.attr('value');
var jsonString = JSON.stringify(cookieObject);
document.cookie = 'cookieObject=' + jsonString;
console.log(jsonString);
}
function setFromCookie(){
var cookieObject = getCookieObject();
for(var inputName in cookieObject)
if(cookieObject.hasOwnProperty(inputName))
$(`.input[name="${inputName}"]`).prop('checked', cookieObject[inputName]);
}
function getCookieObject() {
var nameValueArray = document.cookie.split('=');
var cookieObject = {};
if(nameValueArray.length >= 2)
cookieObject = JSON.parse(nameValueArray[1]);
return cookieObject;
}
$('.input').each(function() {
var $this = $(this);
$this.on('click', function() {
$this.attr('value', String($this.is(':checked')))
updateCookie($this);
});
});
Although I would recomend you to use a URLSearchParams object to encode and decode the parameters, since you are relying on the fact that "=" is not inside the JSON string.

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

jQuery Get data-attribute of all checkbox into a string

I have a list of checkboxes that looks like this:
<input type="checkbox" class="pcb" value="1" data-id="99">
<input type="checkbox" class="pcb" value="2" data-id="98">
<input type="checkbox" class="pcb" value="3" data-id="97">
And originally I only needed the value inside the value attribute of the checked checkbox. I use this javascript/jquery code to do that:
var receiptNos = $("#result input:checkbox:checked").map(function () {
return $(this).val();
}).get();
Using this code gives me: receiptNos = '1,2,3'
Now I need to have another string variable that will hold the content of data-id of all checked checkboxes: receiptNos2 = '99,98,97'
I tried using:
var receiptNos2 = $("#result input:checkbox:checked").attr('data-id').map(function () {
return $(this).val();
}).get();
but it doesn't work. Any ideas?
Instead return $(this).val(); you can use return $(this).data('id');
var receiptNos2 = $("#result input:checkbox:checked").map(function () {
return $(this).data('id')
}).get();

Tricky Javascript logic with Objects, Array and Booleans

I am having a lot of issue trying to figure out this logic. Let me set the stage here:
In the HTML there are some form/input elements type radio. Each of them have an ID assigned to it.
<form>
<input type="radio" name="oneAllowed" id="yesterday" />
<input type="radio" name="oneAllowed" id="today" />
<input type="radio" name="oneAllowed" id="tomorrow" />
</form>
Using Javascript essentially what I am trying to do is loop through the 3 objects, since they all have same name assigned within HTML only a single one can be selected, whichever one is returning true I want grab hold of that result then access the second key:value pair, for example for 'commitYesterday' it would be 'commitYesterday.hasValue();' and dispatch that to a different function for other calculation.
var urgentOrderSelector = function(){
var commitYesterday = {
isChecked: document.getElementById("yesterday").checked,
hasValue: function(){
if (this.isChecked == true) {
return 3;
};
};
};
var commitToday = {
isChecked: document.getElementById("today").checked,
hasValue: function(){
if (this.isChecked == true) {
return 2;
};
};
};
var commitTomorrow = {
isChecked: document.getElementById("tomorrow").checked,
hasValue: function(){
if (this.isChecked == true) {
return 1;
};
};
};
var urgentArray = [commitYesterday.isChecked, commitToday.isChecked, commitTomorrow.isChecked];
for(var i = 0; i <= urgentArray.length-1; i++){
if (urgentArray[i].isChecked == true) {
//This is where I am stuck. I was thinking of doing perhaps the following:
return urgentArray[i].hasValue();
};
}
};
Why don't you change your HTML to this:
<form>
<input type="radio" name="oneAllowed" id="yesterday" value="3" />
<input type="radio" name="oneAllowed" id="today" value="2" />
<input type="radio" name="oneAllowed" id="tomorrow" value="1" />
</form>
And use document.querySelector to get the selected elements:
document.querySelector('[type="radio"][name="oneAllowed"]:checked').value
If you actually need to run specific functions dependend on which radio box is checked you could add an attribute data-fn="fnName" to each input and then create an object with the keys as functions:
var fns = {'fnName1': function () {}, 'fnName2': function() {} …};
And then call the function defined by the Attribute:
fns[document.querySelector('[type="radio"][name="oneAllowed"]:checked').getAttribute('data-fn')]();
Not exactly sure what your end goal is.
But here's a more minified version of your logic. Hope it helps.
var urgentOrderSelector = function(){
var radioDict = {'yesterday':3, 'today':2, 'tomorrow':1};
return radioDict[$('input[name=oneAllowed]:checked').attr('id')];
};
Alternatively, if you wanted to execute some function based on the selection, you could store the function pointers and execute them accordingly, ie:
var funcYesterday = function(){alert('yesterday');};
var funcToday = function(){alert('today');};
var funcTomorrow = function(){alert('tomorrow');};
var funcUrgentOrder = function(){
var radioDict = {
'yesterday' : funcYesterday,
'today' : funcToday,
'tomorrow' : funcTomorrow
};
return radioDict[$('input[name=oneAllowed]:checked').attr('id')]();
};
Or, much simpler, since you are using the 'value' property on your radios:
function urgentOrderSelector = function() {
return $('input[name=oneAllowed]:checked').val();
};

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