Ajax checkbox not updating url on check - javascript

<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

Related

Save and load checkboxes state to file

I want to save state of selected checkbox to a file (whether as a text file or something else) that contains information on what was checked.
I can't use localstorage or cookies, I need it saved as external file so I can save (and load) several files with different checkmarks selected.
It's pretty straightforward, but I can't find any solution that does exactly this, so any help is appreciated.
Simple snippet for reference:
div {
display: table;
}
span {
display: block;
}
input,
label {
display: inline-block;
}
<div>
<span>
<input id="box1" type="checkbox" />
<label for="box1">Checkbox 1</label>
</span>
<span>
<input id="box2" type="checkbox" checked/>
<label for="box2">Checkbox 2</label>
</span>
<span>
<input id="box3" type="checkbox" />
<label for="box3">Checkbox 3</label>
</span>
</div>
<button id="_save">Save</button>
<button id="_load">Load</button>
Ok, I have a solution that does what I needed.
So when you check everything you want from your form, you can save it into localstorage and THEN you can export localstorage as JSON. I found this google extension that handles import and export for the localstorage (in a textual file), but you can always go extra mile and write your own script for that.
Here is JSFiddle for the localstorage so can save whatever input you want and here is chrome extension that handles import and export LocalStorage Manager.
Javascript:
;(function($) {
$.fn.toJSON = function() {
var $elements = {};
var $form = $(this);
$form.find('input, select, textarea').each(function(){
var name = $(this).attr('name')
var type = $(this).attr('type')
if(name){
var $value;
if(type == 'radio'){
$value = $('input[name='+name+']:checked', $form).val()
} else if(type == 'checkbox'){
$value = $(this).is(':checked')
} else {
$value = $(this).val()
}
$elements[$(this).attr('name')] = $value
}
});
return JSON.stringify( $elements )
};
$.fn.fromJSON = function(json_string) {
var $form = $(this)
var data = JSON.parse(json_string)
$.each(data, function(key, value) {
var $elem = $('[name="'+key+'"]', $form)
var type = $elem.first().attr('type')
if(type == 'radio'){
$('[name="'+key+'"][value="'+value+'"]').prop('checked', true)
} else if(type == 'checkbox' && (value == true || value == 'true')){
$('[name="'+key+'"]').prop('checked', true)
} else {
$elem.val(value)
}
})
};
}( jQuery ));
//
// DEMO CODE
//
$(document).ready(function(){
$("#_save").on('click', function(){
console.log("Saving form data...")
var data = $("form#myForm").toJSON()
console.log(data);
localStorage['form_data'] = data;
return false;
})
$("#_load").on('click', function(){
if(localStorage['form_data']){
console.log("Loading form data...")
console.log(JSON.parse(localStorage['form_data']))
$("form#myForm").fromJSON(localStorage['form_data'])
} else {
console.log("Error: Save some data first")
}
return false;
})
});
HTML:
<form action="#" method="get" id="myForm">
<input type="text" name="textfield">
Textfield
<br/>
<input type="number" name="numberfield" />
Numberfield
<br/>
<input type="radio" name="radiofield" value="1" />
<input type="radio" name="radiofield" value="2" />
<input type="radio" name="radiofield" value="3" />
Radiofields
<br/>
<input type="checkbox" name="checkfield">
<input type="checkbox" name="checkfield2">
<input type="checkbox" name="checkfield3">
Checkboxes
<br/>
<select name="selectbox">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
Selectbox
<br/>
<textarea name="textarea"></textarea>
Textarea
<br/>
<hr/>
<button id="_save">Save</button>
<button id="_load">Load</button>
<input type="reset">
</form>

Getting undefined output from jQuery function

I'm getting undefined output from my jQuery function below. I initially assigned empty string to my product_type, I want it to be empty when I don't choose anyone of them, but still getting undefined output. Hopefully, I can have some hints here.
$(function () {
var internal_note = {};
var customer_note = {};
var product_type = "";
var web_camera = "";
var touch_screen = "";
$( "#test" ).on("click" , 'button:not(:disabled)',function(event){
if ($('input[name="product_type"]:checked')){
product_type = $('input[name="product_type"]:checked').attr("value");
};
if($('input[name="web_camera"]:checked')){
web_camera = $('input[name="web_camera"]:checked').attr("value");
};
if($('input[name="touch_screen"]:checked')){
touch_screen = $('input[name="touch_screen"]:checked').attr("value");
};
$('#left_note_list input').each(function(){
internal_note[this.value] = JSON.stringify($(this).val());
});
alert(product_type);
$.ajax({
type: "post",
url: '/insert/',
data: {
'internal_note': JSON.stringify(internal_note),
'product_type': JSON.stringify(product_type),
'web_camera': JSON.stringify(web_camera),
'touch_screen': JSON.stringify(touch_screen)
},
success: function (data) {
swal(data,'You Click the Button','success');
$("#test button:not(:disabled)").text('Done!').attr('disabled', 'disabled');
},
error: function(data){
swal(data.responseText,'You Click the Button', 'error');
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div class="col-md-4">
<h4 class="sub-header" id="product_type">Product Type</h4>
<form>
<div class="radio"><label><input type="radio" name="product_type" value="Laptop">Laptop</label></div>
<div class="radio"><label><input type="radio" name="product_type" value="Tower">Tower</label></div>
<div class="radio"><label><input type="radio" name="product_type" value="Minitower">Minitower</label></div>
<div class="radio"><label><input type="radio" name="product_type" value="Small Form Factor">Small Form Factor</label></div>
</form>
</div><!-- /.col-lg-4 Product Type-->
<div class="text-center" id="test">
<button target="_blank"
class="btn btn-primary ">
Test
</button>
</div>
Your issue is coming from the way you are checking to see is the checkbox is checked. This if check if ($('input[name="product_type"]:checked')). This works, but you do not get a true or false answer back, so you are essentially checking truthy instead. You can either check the length of $('input[name="product_type"]:checked') or you can do this instead
$('input[name="product_type"]').is(":checked")
Here is a good post on how to check whether or not a checkbox is checked
jQuery if checkbox is checked
$(function () {
var internal_note = {};
var customer_note = {};
var product_type = "";
var web_camera = "";
var touch_screen = "";
$( "#test" ).on("click" , 'button:not(:disabled)',function(event){
if ($('input[name="product_type"]').is(":checked")){
product_type = $('input[name="product_type"]:checked').attr("value");
}
if($('input[name="web_camera"]:checked')){
web_camera = $('input[name="web_camera"]:checked').attr("value");
}
if($('input[name="touch_screen"]:checked')){
touch_screen = $('input[name="touch_screen"]:checked').attr("value");
}
$('#left_note_list input').each(function(){
internal_note[this.value] = JSON.stringify($(this).val());
});
alert(product_type);
$.ajax({
type: "post",
url: '/insert/',
data: {
'internal_note': JSON.stringify(internal_note),
'product_type': JSON.stringify(product_type),
'web_camera': JSON.stringify(web_camera),
'touch_screen': JSON.stringify(touch_screen)
},
success: function (data) {
swal(data,'You Click the Button','success');
$("#test button:not(:disabled)").text('Done!').attr('disabled', 'disabled');
},
error: function(data){
swal(data.responseText,'You Click the Button', 'error');
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div class="col-md-4">
<h4 class="sub-header" id="product_type">Product Type</h4>
<form>
<div class="radio"><label><input type="radio" name="product_type" value="Laptop">Laptop</label></div>
<div class="radio"><label><input type="radio" name="product_type" value="Tower">Tower</label></div>
<div class="radio"><label><input type="radio" name="product_type" value="Minitower">Minitower</label></div>
<div class="radio"><label><input type="radio" name="product_type" value="Small Form Factor">Small Form Factor</label></div>
</form>
</div><!-- /.col-lg-4 Product Type-->
<div class="text-center" id="test">
<button target="_blank"
class="btn btn-primary ">
Test
</button>
</div>
It's because your conditional check is never returning false, so it's always assigning the value of product_type, even when nothing is selected. Instead of the check you have, use this:
if ($('input[name="product_type"]:checked').length>0){ ... }
That'll correctly check to ensure you have a checked product type.

How to pass values of selected checkboxes to the javascript function?

I need to pass values of selected check boxes to the javascript method but it does not detect the checkbox.
<form name="cat" method="POST" action="myaction">
<c:forEach items="${items}" var="item">
<input type="checkbox" id="pro" name="pro" value="${item.id}"/>
</c:forEach>
...
<input type="button" value="getItem" onclick="getItem(this.form)"/>
</form>
Javascript
function getItem(frm) {
alert("size:" + frm.pro.length); <<< it returns size:unidentified
var values = "";
for (var i = 0; i < frm.pro.length; i++)
{
if (frm.pro[i].checked)
{
values = frm.pro[i].value + ",";
}
}
alert(values); << it is empty
....
//pass values to the back-end
I think your approach is old fashioned. Here's a jQuery version.
NOTE: you are adding multiple id="pro" and this is just wrong remove it
First add id="form" to your form
Here you can find a fiddle. :D
http://jsfiddle.net/SXffG/3/
HTML:
<form id="form" name="cat" method="POST" action="myaction">
<input type="checkbox" name="pro" value="1"/>
<input type="checkbox" name="pro" value="2"/>
<input type="checkbox" name="pro" value="3"/>
<input type="checkbox" name="pro" value="4"/>
<input type="checkbox" name="pro" value="5"/>
<input type="checkbox" name="pro" value="6"/>
<input type="button" class="getItem" value="getItem"/>
</form>
<div id="info">Click the button</div>
JavaScript
var allVals = [];
$(function() {
$('#form .getItem').click(function() {
allVals = []
$('#form :checked').each(function() {
allVals.push($(this).val());
});
//alert("Values " + allVals);
$.ajax({
type: "POST",
url: "http://localhost:8080/example/ajaxSubmit.action",
data: "allVals=" + allVals,
success: function(response){
$('#info').html("OK! Data [" + allVals + "] Sent with Response:" + response);
},
error: function(e){
$('#info').html("OH NOES! Data[" + allVals +"] Not sent with Error:" + e);
}
});
});
});
var check = document.getElementsByName("pro");
var textArray = [];
for(var c = 0; c < check.length;c++){
if(check[c].checked){
textArray .push(check[c].value);
}
}
textArray = textArray .join("~");
you will get the data as tilde separated. Hope this helps you.

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