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

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);
});

Related

create dropdown with multiple selection in JS

I want to implement a dropdown similar to the one on Booking.com in terms of functionality (I attach a screenshot), but I am encountering some issues and I can't figure out where I'm going wrong. Do you have any suggestions?
HTML
<div class="dropdown">
<input type="text" id="droptxt" class="list" readonly placeholder="Number of guests">
<div id="content" class="content">
<div class="list">
<input type="checkbox" id="rooms" class="list" value="Choose how many rooms" />
<label for="Choose how many rooms" class="list">Choose how many rooms </label>
<input type="hidden" class="list quantity" min="1" value="1" />
</div>
<div class="list">
<input type="checkbox" id="adults" class="list" value="Choose the number of adults" />
<label for="Choose the number of adults" class="list">Choose the number of adults </label>
<input type="hidden" class="list quantity" min="1" value="1" />
</div>
<div class="list">
<input type="checkbox" id="children" class="list" value="Choose the number of children" />
<label for="Choose the number of children" class="list">Choose the number of children </label>
<input type="hidden" class="list quantity" min="1" value="1" />
</div>
</div>
</div>
JavaScript
const txt = document.getElementById('droptxt');
console.log(txt);
const content = document.getElementById('content');
console.log(content);
const checkboxes = document.querySelectorAll('.list input[type="checkbox"]');
const quantity = document.querySelectorAll('.list input[type="number"]');
txt.addEventListener('click', function() {
content.classList.toggle('show');
});
// Close the dropdown if the user clicks outside of it
window.onclick = function(e) {
if (!e.target.matches('.list')) {
if (content.classList.contains('show')) content.classList.remove('show');
}
};
checkboxes.forEach(function(checkbox, index) {
checkbox.addEventListener('click', function() {
quantity[index].type = (checkbox.checked) ? 'number' : 'hidden';
calc();
});
});
quantity.forEach(function(input) {
input.addEventListener('input', calc);
});
function calc() {
let arr = [];
for (let i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
arr.push(quantity[i].value + ' x ' + checkboxes[i].value);
}
}
txt.value = arr.join(', ');
}
const quantity = document.querySelectorAll('.list input[type="number"]');
in this line you are selecting input[type="number"] but in your html there is no input which type is number. use this
const quantity = document.querySelectorAll('.list input[type="hidden"]');
it will solve your problem

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

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.

use implode and ajax to insert checkbox values

i want to insert my checkbox values, i dont know how to take all the values using ajax and use implode to insert them in one row.
// this is my javascript where i take the data ,
function saveData() {
var modsubj = $('#modalsubject').val();
var modsect = $('#modalsection').val();
var modday = $('#modalday').val();
var modstart = $('#modalstarttime').val();
var modend = $('#modalendtime').val();
var moduser = $('#userID').val();
$.ajax({
type: "POST",
url: "modal.funcs.php?p=add",
data: "subj=" + modsubj + "&sect=" + modsect + "&day=" + modday + "&start=" + modstart + "&end=" + modend + "&user=" + moduser
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkbox">
<label class="checkbox-inline">
<input type="checkbox" id="modalday[]" name="modalday[]" value="M">Monday
</label>
</div>
<div class="checkbox">
<label class="checkbox-inline">
<input type="checkbox" id="modalday[]" name="modalday[]" value="T">Tuesday
</label>
</div>
<div class="checkbox">
<label class="checkbox-inline">
<input type="checkbox" id="modalday[]" name="modalday[]" value="W">Wednesday
</label>
</div>
<div class="checkbox">
<label class="checkbox-inline">
<input type="checkbox" id="modalday[]" name="modalday[]" value="Th">Thursday
</label>
</div>
<div class="checkbox">
<label class="checkbox-inline">
<input type="checkbox" id="modalday[]" name="modalday[]" value="F">Friday
</label>
</div>
this is my php function, i used the implode function so that i can insert the data on one row.
$page = isset($_GET['p'])?$_GET['p']:'';
if($page=='add'){
foreach ($_POST['day'] as $key => $value) {
$subj = $_POST['subj'];
$sect = $_POST['sect'];
$day = implode("",$_POST['day']);
$strTime = $_POST['start'];
$endTime = $_POST['end'];
$user_id = $_POST['user'];
}
$auth_user->createSchedule($subj,$sect,$day,$strTime,$endTime,$user_id);
$schedRow = $auth_user->readSchedule();
} else if ($page=='edit') {
}
Here is how to send a list to the server
You can explode the day to get an array of days
To add more items, add a comma and more key values:
data: { day: modday.join(","),
subj:$('#modalsubject').val() // no comma on the last
}
$(function() {
$("#save").on("click", function() {
saveData();
});
});
function saveData() {
var modday = [];
$('.modalday:checked').each(function() {
modday.push(this.value);
});
console.log(modday);
$.ajax({
type: "POST",
url: "modal.funcs.php?p=add",
data: { day: modday.join(",") }
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkbox">
<label class="checkbox-inline">
<input type="checkbox" class="modalday" name="modalday[]" value="M">Monday
</label>
</div>
<div class="checkbox">
<label class="checkbox-inline">
<input type="checkbox" class="modalday" name="modalday[]" value="T">Tuesday
</label>
</div>
<div class="checkbox">
<label class="checkbox-inline">
<input type="checkbox" class="modalday" name="modalday[]" value="W">Wednesday
</label>
</div>
<div class="checkbox">
<label class="checkbox-inline">
<input type="checkbox" class="modalday" name="modalday[]" value="Th">Thursday
</label>
</div>
<div class="checkbox">
<label class="checkbox-inline">
<input type="checkbox" class="modalday" name="modalday[]" value="F">Friday
</label>
</div>
<button id="save">Save</button>
I tried this myself, and I think most of the action can occur in your saveData function, not in PHP.
I'm assuming you will change your ids to a class instead, as id's should be unique:
<input type="checkbox" class="modalday" name="modalday[]" value="M">Monday
Check this out:
function saveData() {
var modsubj = $('#modalsubject').val();
var modsect = $('#modalsection').val();
var moddayAll = document.getElementsByClassName('modalday');
var modday = [];
for (let i = 0; i < moddayAll.length; i++) {
if (moddayAll[i].checked) {
modday.push(moddayAll[i].value);
}
}
var modstart = $('#modalstarttime').val();
var modend = $('#modalendtime').val();
var moduser = $('#userID').val();
var add = 'add';
$.post("modal.funcs.php", {p:add, subj:modsubj, sect:modsect, day:modday.join(","), start:modstart, end:modend, user:moduser},
function( data ) {
// do whatever you want with data returned from modal.funcs.php
}
);
};
I just used vanilla JavaScript to select all the modalday elements, then loop through them and add the values (M, T, W, etc...) of the ones that are checked to the modday array:
var moddayAll = document.getElementsByClassName('modalday');
var modday = [];
for (let i = 0; i < moddayAll.length; i++) {
if (moddayAll[i].checked) {
modday.push(moddayAll[i].value);
}
}
Then, since you are using the POST method anyway, I used JQuery's .post(), and passed the 'p' param along with the data, instead of in a query string. You'll notice this is where the modday array is turned to a string with the join() call as well:
var add = 'add';
$.post("modal.funcs.php", {p:add, subj:modsubj, sect:modsect, day:modday.join(","), start:modstart, end:modend, user:moduser},
function( data ) {
// do whatever you want with data returned from modal.funcs.php
}
);
Then, in modal.funcs.php, you can just get the values from the $_REQUEST variable and pass them to your functions:
<?php
$page = $_REQUEST['p'];
if ($page == 'add') {
$subj = $_REQUEST['subj'];
$sect = $_REQUEST['sect'];
$day = $_REQUEST['day'];
$strTime = $_REQUEST['start'];
$endTime = $_REQUEST['end'];
$user_id = $_REQUEST['user'];
$auth_user->createSchedule($subj,$sect,$day,$strTime,$endTime,$user_id);
$schedRow = $auth_user->readSchedule();
} else if ($page=='edit') {
}
$_REQUEST['day] will be a comma-separated string of the values of the checkboxes that were checked. If you need to do further processing of the array here, you can add another step to do so.

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(','));.

Categories