how to get checked values from a checkbox-group using jquery - javascript

I want to get the values of all the checked checkboxes in the checkbox-group.
<div class="checkbox-group">
<div class="checkbox">
<label for="checkbox-group-1501481486714-preview-0">
<input name="checkbox-group-1501481486714-preview[]" class="" id="checkbox-group-1501481486714-preview-0" value="physics" type="checkbox" checked="checked">physics</label>
</div>
<div class="checkbox"><label for="checkbox-group-1501481486714-preview-1"><input name="checkbox-group-1501481486714-preview[]" class="" id="checkbox-group-1501481486714-preview-1" value="math" type="checkbox">math</label>
</div>
<div class="checkbox"><label for="checkbox-group-1501481486714-preview-2">
<input name="checkbox-group-1501481486714-preview[]" class="" id="checkbox-group-1501481486714-preview-2" value="chemistry" type="checkbox">chemistry</label>
</div>
</div>
Following is script code
document.getElementById('btn').addEventListener('click', function() {
$(document).ready(function(){
var x = $(".userform").find(":input");
$.each(x, function(i, field){
if(field.type == "text")
{
$("#results").append("name: "+field.name + ": " +"Value: "+ field.value +"<br>");
}
else if(field.type == "checkbox")
{
var result = $('input[type="checkbox"]:checked');
if(result.length > 0)
{
$("#results").append("this is checked "+"name: "+field.name + ": " +"Value: "+ field.value +"<br>");
}
else{
$("#results").append("this is unchecked");
}
}
});
});
});
When I leave all uncheck then it gives this output
this is unchecked
this is unchecked
this is unchecked
but when I check any it gives this output
this is checked name: checkbox-group-1500619332922: Value: on
this is checked name: checkbox-group-1500619332922: Value: on
this is checked name: checkbox-group-1500619332922: Value: on
Thanks in Advance

You can do this simple loop:
var values = [];
$('input[type="checkbox"]:checked').each(function(i,v){
values.push($(v).val());
});
if you want only form a group lets say .group then change the selector to
$('.group input[type="checkbox"]:checked')
demo:
$('input[type="checkbox"]').change(function() {
$('.checkbox-group').each(function() {
var values = [];
$(this).find('input[type="checkbox"]:checked').each(function(i, v) {
values.push($(v).val());
});
console.log(values);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkbox-group">
<div class="checkbox">
<label for="checkbox-group-1501481486714-preview-0">
<input name="checkbox-group-1501481486714-preview[]" class="" id="checkbox-
group-1501481486714-preview-0" value="option-1" type="checkbox"
checked="checked">Option 1</label>
</div>
<div class="checkbox"><label for="checkbox-group-1501481486714-preview-1">
<input name="checkbox-group-1501481486714-preview[]" class="" id="checkbox-
group-1501481486714-preview-1" value="option-2" type="checkbox">Option
2</label>
</div>
</div>
<div class="checkbox-group">
<div class="checkbox">
<label for="checkbox-group-1501481486714-preview-0">
<input name="checkbox-group-1501481486714-preview[]" class="" id="checkbox-
group-1501481486714-preview-0" value="option-1 group-2" type="checkbox"
checked="checked">Option 1</label>
</div>
<div class="checkbox"><label for="checkbox-group-1501481486714-preview-1">
<input name="checkbox-group-1501481486714-preview[]" class="" id="checkbox-
group-1501481486714-preview-1" value="option-2 group-2" type="checkbox">Option
2</label>
</div>
</div>

You can try below demo code for get selected value.
var demo = $("input[type="checkbox"]:checked").map(function() { return $(this).val(); }).get();
you can try.

Related

How can I add values from checkboxes to a URL string as grouped parameters?

I saw lots of similar question where you can extract the values of Checkboxes based on the check uncheck and add them to URL, but if we have different categories of checkbox group, separate them with &.
Example:
$(document).ready(function() {
var swapRelation = "";
$("input[type=checkbox]").click(function(e) {
var seasoning = "",
parentRelation = "",
tempArray = [];
$("input:checked").each(function() {
tempArray.push($(this).attr("name").replace(/\s/g, ''));
parentRelation = $(this).closest(".wrapper").find('.catName').text().trim();
parentRelation = parentRelation.replace(/\s/g, '');
});
if (tempArray.length !== 0) {
seasoning += `${parentRelation}=` + tempArray.toString();
// if (swapRelation == parentRelation) {
// // seasoning+=`&${parentRelation}=`+tempArray.toString();
// seasoning += `${parentRelation}=` + tempArray.toString();
// }else {
// }
//tempArray = [];
swapRelation = parentRelation;
}
console.log("example.com?" + seasoning);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div class="catName">Fruits</div>
<div class="checkBoxWrap">
<input class="input__field" type="checkbox" name="apple" id="input-5">
<input class="input__field" type="checkbox" name="banana" id="input-6">
<input class="input__field" type="checkbox" name="mango" id="input-7">
</div>
</div>
<div class="wrapper">
<div class="catName">Vaegs</div>
<div class="checkBoxWrap">
<input class="input__field" type="checkbox" name="Okra" id="input-8">
<input class="input__field" type="checkbox" name="Patato" id="input-9">
<input class="input__field" type="checkbox" name="Tamato" id="input-10">
</div>
</div>
<div class="wrapper">
<div class="catName">Rivers</div>
<div class="checkBoxWrap">
<input class="input__field" type="checkbox" name="Ganga" id="input-11">
<input class="input__field" type="checkbox" name="yamuna" id="input-12">
<input class="input__field" type="checkbox" name="thames" id="input-13">
</div>
</div>
Expected Result on multiple Selections:
URL?Fruits=banana,mango&Vegs=okra,patato&Rivers=ganga,whateverSelected
You can use URLSearchParams to build your query string.
var usp = new URLSearchParams();
document.querySelectorAll('.wrapper').forEach((wrapperDiv)=> {
var category = wrapperDiv.querySelector('.catName').textContent;
var checkedBoxes = wrapperDiv.querySelectorAll('input[type="checkbox"]:checked');
var values = Array.from(checkedBoxes, cb=>cb.name).join('');
usp.append(category,values);
});

jQuery: How to uncheck random checkboxes in div after checking all?

When onClick on link occurs, all checkboxes present in that div are checked.
function initSelectAll() {
$("form").find("a.selectAll").click(function() {
var cb = $(this).closest("div").find("input[type=checkbox]");
cb.not(":checked").click().length || cb.click();
//........WANT TO UNCHECK checkboxes with class="file" where link id is 'id="ninapaya"'; how to do that?......
return false;
});
}
initSelectAll();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div>
Select
<span class="kukapaya">(alle)</span>
<br>
<input type="checkbox" class="document" name="check2">
<input type="checkbox" class="document" name="check2">
<br>
<input type="checkbox" class="File">
<input type="checkbox" class="File">
</div>
</form>
Requirement: We should not check the checkboxes with class="File".
JSFiddle: https://jsfiddle.net/k4d6zpay/
It could be simplified using .prop(.prop( propertyName, function )) and using :not selector
$("form").find("a.selectAll").click(function() {
$(this).closest("div").find("input[type='checkbox']:not('.File')").prop('checked', function() {
return !this.checked;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form>
<div>
Select
<span class="kukapaya">(alle)</span>
<br>
<input type="checkbox" class="document" name="check2">
<input type="checkbox" class="document" name="check2">
<br>
<input type="checkbox" class="File">
<input type="checkbox" class="File">
</div>
</form>
try this:
function initSelectAll() {
$("form").find("a.selectAll").click(function() {
var cb = $(this).closest("div").find("input[type=checkbox]");
cb.not(":checked").not('.File').click().length || cb.click();
return false;
});
}
initSelectAll();
Also update in your jsfiddle link: https://jsfiddle.net/k4d6zpay/1/
function initSelectAll() {
$("form").find("a.selectAll").click(function() {
var cb = $(this).closest("div").find("input[type=checkbox]:not(.File)");
cb.not(":checked").click().length || cb.click();
//........WANT TO UNCHECK checkboxes with class="file" where link id is 'id="ninapaya"';
$(this).closest("div").find("input[type=checkbox][id='ninapaya'].File").prop('checked',false);
return false;
});
}
initSelectAll();

How to serialize checkbox value through searilizedarray()?

My question is how to serialize checkbox value and textbox value together in one array through searilizedarray()...
now i am getting something like this
[{"name":"text_input","value":"kalpit"},
{"name":"wpc_chkbox[]","value":"Option one"},
{"name":"wpc_chkbox[]","value":"Option two"},
{"name":"wpc_chkboxasdf[]","value":"Option one"},
{"name":"wpc_chkboxasdf[]","value":"Option two"},
{"name":"wpc_inline_chkbox[]","value":"1"},
{"name":"wpc_inline_chkbox[]","value":"2"},
{"name":"wpc_inline_chkbox[]","value":"3"},
{"name":"wpc_radios","value":"Option one"}]
but it should be like
[{"name":"text_input","value":"kalpit"},
{"name":"wpc_chkbox[]","value":"[Option one,Option Two]"},
{"name":"wpc_chkboxasdf[]","value":"[Option one,Option Two]"},
{"name":"wpc_inline_chkbox[]","value":"[1,2,3]"},
{"name":"wpc_radios","value":"Option one"}]
i am using var form = $('.wpc_contact').serializeArray(); to get form data
this is my html sample which I am generating dynamically using drag and drop future..
<form method="POST" name="1" class="form-horizontal wpc_contact" novalidate="novalidate">
<fieldset>
<div id="legend" class="">
<legend class="">Demo</legend>
<div id="alert-message" class="alert hidden" style="color: red;"></div>
</div>
<div class="control-group">
<label class="control-label">Checkboxes</label>
<div class="controls" name="wpc_chkbox" req="yes">
<input type="checkbox" value="Option one" id="wpc_chkbox_0" name="wpc_chkbox[]" req="yes"> Option one
<input type="checkbox" value="Option two" id="wpc_chkbox_1" name="wpc_chkbox[]" req="yes"> Option two
</div>
</div>
<div class="control-group">
<div class="controls" name="wpc_inline_chkbox" req="yes">
<input type="checkbox" value="1" name="wpc_inline_chkbox[]" id="wpc_inline_chkbox_0" req="yes"> 1
<input type="checkbox" value="2" name="wpc_inline_chkbox[]" id="wpc_inline_chkbox_1" req="yes"> 2
<input type="checkbox" value="3" name="wpc_inline_chkbox[]" id="wpc_inline_chkbox_2" req="yes"> 3
</div>
</div>
<div class="control-group">
<div class="controls">
<button class="btn btn-success">Button</button>
</div>
</div>
</fieldset>
</form>
Thanks in advance
Try this:
var cacheObject = {};//tmp cache for form elements name/values pairs
var serArr = $('.wpc_contact').serializeArray();
//set values of elements to cacheObject
$.each(serArr, function (arrayIndex,obj) {
if (cacheObject[obj.name]) {
cacheObject[obj.name].push(obj.value);
} else {
cacheObject[obj.name] = [obj.value];
}
});
//create new serialized array
var newSerArr = [];
$.each(cacheObject, function (key, value) {
var obj = {};
obj[key] = value;
newSerArr.push(obj);
});
console.log(newSerArr);//looks like serializeArray
This one makes a different array and elements of same name are grouped together.
var form_data = $(".wpc_contact").serializeArray();
var form_array = {}; //final array where all the values will be stored
$.each(form_data, function(i, element) {
if(jQuery('input[name="'+element.name+'"]:checked').length>0)
{
replaced = element.name.replace('[]',''); //removing [] from the input name
form_array[replaced]={};
jQuery('input[name="'+element.name+'"]:checked').each(function(j,ind){
form_array[replaced][j] = jQuery(this).val();
});
}
else
{
form_array[element.name] = element.value;
}
});
console.log(form_array);
You can access as:
alert(form_array['wpc_chkbox'][0]); //no '[]' in the key

Jquery append values to a url as query string

I tried some jquery to append my check box checked values to the url as query string the code is working nice but when I check more than one checkbox the url will like this.....
Localhost:355/searchdatabase/?manufacturer=LG&manufacturer=Samsung&manufacturer=Test
But I need the url Like
Localhost:355/searchdatabase/?manufacturer=LG,Samsung,Test
here is my code
$(document).ready(function () {
$('input[type="checkbox"]').on('change', function (e) {
var data = [],
loc = $('<a>', { href: window.location })[0];
$('input[type="checkbox"]').each(function (i) {
if (this.checked) {
data.push(this.name + '=' + this.value);
}
});
data = data.join('&');
$.post('/ajax-post-url/', data);
if (history.pushState) {
history.pushState(null, null, loc.pathname + '?' + data);
}
});
});
My checkbox list groups code here
<div class="rowElem">
<input type="checkbox" name="manufacturer" id="">
<label>LG</label>
</div>
<div class="rowElem">
<input type="checkbox" name="manufacturer" id="">
<label>Samsung</label>
</div>
<div class="rowElem">
<input type="checkbox" name="manufacturer" id="">
<label>Test</label>
</div>
<div class="rowElem">
<input type="checkbox" name="material" id="">
<label>iron</label>
</div>
<div class="rowElem">
<input type="checkbox" name="material" id="">
<label>steel</label>
</div>
<div class="rowElem">
<input type="checkbox" name="material" id="">
<label>copper</label>
</div>
I need Manufacturer as a group and material as another..
You can add all manufacturers to separated array and then add as one field.
var manufacturers = [];
if (this.checked) {
if (this.name === 'manufacturers') {
manufacturers.push(this.value);
} else {
data.push(this.name + '=' + this.value);
}
}
And before data = data.join('&'); add data.push('manufacturers=' + manufacturers.join(','));.

how to store the checked value from checked box and radio box in local storage

I am using JQuery Mobile
I want to display the value in another page which i get from local storage
It Should been check which is been checked in page1
In HTML5:-
<div data-role="page" id="page1">
<div data-role="content">
<div data-role="fieldcontain">
<form>
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Levels:</legend>
<input type="checkbox" value="One" name="one" id="checkbox-h-2a" class="custom1">
<label for="checkbox-h-2a">One</label>
<input type="checkbox" value="None" name="one" checked="checked" id="checkbox-h-2c" class="custom1">
<label for="checkbox-h-2c">None</label>
</fieldset>
</form>
</div>
<div data-role="fieldcontain">
<form>
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Mode:</legend>
<input type="radio" name="Two" id="radio-choice-h-2a" value="On" checked="checked" class="custom2">
<label for="radio-choice-h-2a">On</label>
<input type="radio" name="Two" id="radio-choice-h-2b" value="Off" class="custom2">
<label for="radio-choice-h-2b">Off</label>
</fieldset>
</form>
</div>
</div>
</div>
<div data-role="page" id="page2">
<div data-role="content">
<div data-role="fieldcontain">
<form>
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Levels:</legend>
<input type="checkbox" name="checkbox-h-2a" id="checkbox-h-2a" class="custom1">
<label for="checkbox-h-2a">One</label>
<input type="checkbox" name="checkbox-h-2c" id="checkbox-h-2c" class="custom1">
<label for="checkbox-h-2c">None</label>
</fieldset>
</form>
</div>
<div data-role="fieldcontain">
<form>
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Mode:</legend>
<input type="radio" name="radio-choice-h-2" id="radio-choice-h-2a" value="on" class="custom2">
<label for="radio-choice-h-2a">Steward</label>
<input type="radio" name="radio-choice-h-2" id="radio-choice-h-2b" value="off" class="custom2">
<label for="radio-choice-h-2b">Guest</label>
</fieldset>
</form>
</div>
</div>
</div>
In Jquery:-
function getRadioCheckedValue(radio_name)
{
var oRadio = $("input[type='radio']");
for(var i = 0; i < oRadio.length; i++)
{
if(oRadio[i].checked)
{
//return oRadio[i].value;
localStorage.setItem("mode", oRadio[i].value);
}
}
return '';
}
function showSelectedNames(){
var count = $("#checkid input:checked").length;
var str = '';
for(i=0;i<count;i++){
if(i == count-1){
str += $("#checkid input:checked")[i].value;
localStorage.setItem("level", str);
}
else{
str += $("#checkid input:checked")[i].value+',';
localStorage.setItem("level", str);
}
}
//alert("You selected----"+str);
}
Now Plz help me out how to set the value in Page 2 which is been checked in Page1
The simplest way is to store values of checkboxes and radio buttons into an array and then save it to localStorage. However, note that localStorage doesn't accept arrays, so you need to JSON.stringify() before saving it into localStorage and then JSON.parse() to convert it back into a readable array.
Here is how you can collect values of all checkboxes and radio buttons, store them and then read them on next page.
$(document).on("pagebeforehide", "[data-role=page]", function () {
// variables
var elements = [],
id = '',
value = '';
// push values of checkboxes and radio buttons into an array
$("[type=checkbox], [type=radio]", this).each(function () {
id = $(this)[0].id;
value = $(this).prop("checked");
elements.push({
"id": id,
"value": value
});
});
// convert array into a string
// in order store it into localStorage
localStorage["values"] = JSON.stringify(elements);
});
$(document).on("pagebeforeshow", "[data-role=page]", function () {
// active page
var active = $.mobile.activePage;
// parse array of checkboxes and radio buttons
var read_array = JSON.parse(localStorage["values"]);
// check/uncheck checkboxes and radio buttons
$.each(read_array, function (e, v) {
var check_id = "#" + v.id,
check_value = v.value;
$(check_id, active).prop("checked", check_value).checkboxradio("refresh");
});
});
Note: elements id should be the same on other pages.
Demo

Categories