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(','));.
Related
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);
});
<script>
$('input[type="checkbox"]').on('change', function(e){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var data = {},
fdata = [],
loc = $('<a>', {href:window.location})[0];
$('input[tpye="checkbox"]').each(function(i){
if(this.checked){
if(!data.hasOwnProperty(this.name)){
data[this.name] = [];
}
data[this.name].push(this.value);
}
});
$.each(data, function(k, v){
fdata[k] = [v.join(',')];
});
fdata = fdata.join('&');
$.post('/wines/all-wines/', fdata);
console.log(fdata);
if(history.pushState){
history.pushState(null, null, loc.pathname+'?'+fdata);
}
});
<div class="panel-body">
<div class="rowElem">
<input type="checkbox" name="country" value="1" id="">
<label>Color #1</label>
</div>
<div class="rowElem">
<input type="checkbox" name="country" value="2" id="">
<label>Color #2</label>
</div>
<div class="rowElem">
<input type="checkbox" name="country" value="3" id="">
<label>Color #3</label>
</div>
</div>
I'm using laravel thats why i'm passing X-CSRF token. What i want to achieve is when user clicks on one or more checkboxes it automatically change url to something like this : link.com/products/all-products?country=1,2,3,4,5
but after clicking on checkboxes it only change url to : link.com/products/all-products? and thats mainly it. What could be wrong in the code? Thank you very much!
In addition to what nbkHope pointed out you need the following:
$.each(data, function(k, v){
fdata[k] = [v.join(',')];
});
var countryArr = fdata["country"];
fdata = countryArr.join('&');
Your array looks like this: {country: Array()}, so you need to get country out of fdata and then call join.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join
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.
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();
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