checkbox - Check uncheck functionality is not working - javascript

My situation :
I am working on an shopping cart application and it contains some filters:
Filter by color (checkboxes)
Filter by style (checkboxes)
on selecting some of the colors my url becomes like this:
http://example.com/women/try.php?color=10,11,12,13
My issue :
On unchecking some colors the related params are not getting cleared from the url.
Also when I select some styles , I want the url to be like this:
http://example.com/women/try.php?color=10,11,12,13&style=1,2,3
Please help me how to achieve this functionality.
My code :
<?php
$colors = $_GET['color'];
$sel_colors = explode(',', $colors);
foreach($sel_colors as $k=>$v) {
$c['check'][$v] = $v;
}
for($i=10;$i<=14;$i++) { ?>
<input type="checkbox" name="color[]" value="<?php echo $i; ?>" <?php echo $check_value = ($c['check'][$i]) ? 'checked' : '0'; ?> >
<label>Color #<?php echo $i.'--'.$check_value; ?></label><?php
}
?><br/><br/><br/>
<input type="checkbox" name="type" value="1" >
<label>style #1</label>
<input type="checkbox" name="type" value="2" >
<label>style #2</label>
<input type="checkbox" name="type" value="3" >
<label>style #3</label>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js" ></script>
<script type="text/javascript">
var baseUrl = 'http://website/women/try.php?color=';
$(document).ready(function () {
// listen to change event (customize selector to your needs)
$('input[type=checkbox]').change(function (e) {
e.preventDefault();
if ($(this).is(':checked')) {
// read in value
var queryString = $(this).val();
// loop through siblings (customize selector to your needs)
var s = $(this).siblings();
$.each(s, function () {
// see if checked
if ($(this).is(':checked')) {
// append value
queryString += ',' + $(this).val();
}
});
// jump to url
window.location = baseUrl + queryString;
}
});
});
</script>

Here is a code snippet of working solution. Name of the color checkbox is changed from color[] to just color
var baseUrl = 'http://website/women/try.php?';
$(document).ready(function () {
// listen to change event (customize selector to your needs)
$('input[type=checkbox]').change(function (e) {
//Get all the selected color values
var queryString = "color="+$('[name="color"]:checked')
.map(function() {return this.value;}).get().join(',');
//Append all the selected styles
queryString += "&style="+$('[name="type"]:checked').map(function() {return this.value;}).get().join(',');
//reload page - commented for this snippet
//window.location = baseUrl + queryString;
alert(baseUrl + queryString);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Color filter -->
<input type="checkbox" name="color" value="1" checked >
<label>Color 1</label>
<input type="checkbox" name="color" value="2" checked >
<label>Color 2</label>
<input type="checkbox" name="color" value="3" checked >
<label>Color 3</label>
<input type="checkbox" name="color" value="4" checked >
<label>Color 4</label>
<BR><BR>
<!-- Style filter -->
<input type="checkbox" name="type" value="1" >
<label>style #1</label>
<input type="checkbox" name="type" value="2" checked>
<label>style #2</label>
<input type="checkbox" name="type" value="3" checked>
<label>style #3</label>

Use map() function to get all checked color and style checkbox values like following.
var baseUrl = 'http://website/women/try.php?color=';
$('input[name="color[]"], input[name="type"]').change(function () {
var colors = $('input[name="color[]"]:checked').map(function () { return this.value; }).get().join();
var styles = $('input[name="type"]:checked').map(function () { return this.value; }).get().join();
window.location = baseUrl + colors + '&style=' + styles;
});

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>

Retrieveing the values from database selecting or deselecting the checkboxes JQuery

There is a problem in my jQuery. I want to retrieve the data from the database using AJAX.How I select and pass to the php file these values and get the multiple values.
For Example- when I select the checkbox the ajax will return the value of the selected checkbox. If I unselect the same checkbox then the value will be removed.
here the checkboxes are:
checkboxes.php
<div class="block1">
<label><input type="checkbox" name="checkbox[]" id="extra" value="deep cleaning"/>Deep Cleaning</label>
<label><input type="checkbox" name="checkbox[]" id="extra" value="dishes"/>Dishes</label>
<label><input type="checkbox" name="checkbox[]" id="extra" value="move in/out"/>Move in/out</label>
</div>
<div class="block1">
<label><input type="checkbox" name="checkbox[]" id="extra" value="inside cabinets"/>Inside Cabinets</label>
<label><input type="checkbox" name="checkbox[]" id="extra" value="inside fridge" />Inside Fridge</label>
<label><input type="checkbox" name="checkbox[]" id="extra" value="inside oven" />Inside Oven</label>
</div>
<div class="block1">
<label><input type="checkbox" name="checkbox[]" id="extra" value="interior windows" />Interior windows</label>
<label><input type="checkbox" name="checkbox[]" id="extra" value="laundry + folding" />Laundry + Folding</label>
<label><input type="checkbox" name="checkbox[]" id="extra" value="green cleaning" />Green Cleaning</label>
</div>
<div class="block1">
<label><input type="checkbox" name="checkbox[]" id="extra" value="organization" />Organization</label>
<label><input type="checkbox" name="checkbox[]" id="extra" value="wipe window blinds" />Wipe Window Blinds</label>
</div>
</div>
<span id="cost"></span>
</div>
here the jQuery:
$(document).ready(function() {
var check=[];
$('input[type=checkbox]').on('change', function() {
var check=$(this).val();
console.log($(this).val());
$.ajax({
type:'POST',
data:{ "extra" : check},
dataType : "JSON",
url : "login.php",
success:function(response){
if(response){
totalCost=10+response;
$('#cost').text(totalCost);
}
}
});
});
});
here the php code-
if (isset($_POST['extra'])) {
$query=mysqli_query($con,"select price from extras where name_of_extra ='$_POST[extra]'");
while ($row = mysqli_fetch_array($query)) {
echo json_encode($row['price'],JSON_NUMERIC_CHECK);
}
}
database image-
I want to check the multiples and recieve multiple values through ajax and when i unselect the checkboxes then the value will remove from the span total. if there is any mistake then i m sorry. i am a bigner. i hope you all will support me do better thnku in advance.
HTML
<label>Total amount : </label>
<span id="totalCost">0</span>
JS
$(document).ready(function () {
var check = [];
$('input[type=checkbox]').on('change', function () {
var checked = 0; // assigning ZERO for unchecked
if ($(this).prop('checked') == true) { // checking checkbox status
checked = 1; // ONE for checked
}
var totalCost = $("#totalCost").text(); // getting previous totalcost
var check = $(this).val();
// two parameters
// data json object
// callback function
getData({"extra": check}, function (response) {
var content = '';
if (response) { //response is json object
if (checked) { // if checkbox is checked
content = '<div id="' + response['id'] + '">' + response['price'] + '</div>';
//create another variable which have div with price and id
totalCost = parseInt(totalCost) + response['price'];
// add new price in previous price
} else {
$('#' + response['id']).remove();
// remove price div targeting with id
totalCost = parseInt(totalCost) - response['price'];
// subtract price from previous price
}
$("#cost").prepend(content); // prepend new content
$("#totalCost").html(totalCost);
}
});
});
function getData(data, callback) {
$.ajax({
type: 'POST',
data: data,
dataType: "JSON",
url: "login.php",
success: callback
});
}
});
Changes in php code
if (isset($_POST['extra'])) {
$query=mysqli_query($con,"select * from extras where name_of_extra ='$_POST[extra]'");
while ($row = mysqli_fetch_array($query)) {
echo json_encode($row,JSON_NUMERIC_CHECK);
}
}

javascript change and send multiple checkbox values

H, I have 4 checkboxes that i need to set values when clicked and unclicked. I have code that works for the first one but struggling to make it work with the other 3?
The code is
<label><input type="checkbox" name="colorCheckbox" value="red"> Return journey required?</label>
<div align="left"> <label><input type="checkbox" name="signs" id="signs"> Non sign written</label></div>
<div align="left"> <label><input type="checkbox" name="disabled" id="disabled"> Disabled access</label></div>
<div align="left"> <label><input type="checkbox" name="female" id="female"> Female driver</label></div>
and the js that works for the first on is :
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
var inputValue = $(this).attr("value");
$("." + inputValue).toggle();
if (this.checked){
document.getElementById("return_required").value = "YES";
}
else {
document.getElementById("return_required").value = "NO";
}
});
});
Because they don't have a value like the first one. They have an id.
You are getting the input value and working on it, so if the input don't has a value, you won't be able to select it.
var inputValue = $(this).attr("value"); // Offending line, because only your first input has a value.
$("." + inputValue).toggle();
The easiest way would be to check the name of the clicked element using this.name and manually match it to the checkboxes, then code the logic for each checkbox. An example is provided below:
$(document).ready(function() {
$('input[type="checkbox"]').click(function() {
var inputValue = $(this).attr("value");
$("." + inputValue).toggle();
if (this.name == "colorCheckbox")
if (this.checked) {
document.getElementById("return_required").value = "YES";
} else {
document.getElementById("return_required").value = "NO";
}
else if (this.name == "signs") {
console.log("signs"); // replace with logic
} else if (this.name == "disabled") {
console.log("disabled"); // replace with logic
} else if (this.name == "female") {
console.log("female"); // repalce with logic
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input type="checkbox" name="colorCheckbox" value="red"> Return journey required?</label>
<div align="left"> <label><input type="checkbox" name="signs" value="signs"> Non sign written</label></div>
<div align="left"> <label><input type="checkbox" name="disabled" value="disabled"> Disabled access</label></div>
<div align="left"> <label><input type="checkbox" name="female" value="female"> Female driver</label></div>
<br>
<input id="return_required" value="NO"></input>

jquery: remove the selected value if checkbox is unchecked

I'm displaying list of items with checkbox, if checkbox is checked the value of selected item is displayed in different div.
Now, if I uncheck the checkbox I should remove the items displayed in the div.
Please help me how to fix this?
$('input[name="selectedItems1"]').click(function(){
if (this.checked) {
}else{
//what should go here
}
});
This example can help you:
html
<input type="checkbox" name="selectedItems1" value="val1" />
<input type="checkbox" name="selectedItems1" value="val2" />
<input type="checkbox" name="selectedItems1" value="val3" />
<div id="result"></div>
jquery
$('input[name="selectedItems1"]').click(function(){
if (this.checked) {
var span = "<span id='" + this.value + "'>" + this.value + "</span>";
$("#result").append(span);
}else{
$("#" + this.value).remove();//what should go here
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="selectedItems1" value="val1" />
<input type="checkbox" name="selectedItems1" value="val2" />
<input type="checkbox" name="selectedItems1" value="val3" />
<div id="result"></div>
Here is a way to accomplish your task. The following way also preserves the order in which the selected data is displayed.
var selectedItemsContainer = $('#selected');
var items = $('input[name="items"]');
items.on('change', function(){
selectedItemsContainer.empty();
var appendData = '';
$.each(items, function(i, item)
{
if ($(item).prop('checked'))
{
appendData +=$(item).val() + ' ';
}
});
selectedItemsContainer.append(appendData);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="checkbox" name="items" value="Data 1">Data 1
<input type="checkbox" name="items" value="Data 2">Data 2
<input type="checkbox" name="items" value="Data 3">Data 3
<br>
<div id="selected"></div>

array of checkbox value checked and unchecked

I have this function, when I checked one or more checkbox the function load the value of the checked checkbox...but when I unchecked one or more check box the function show an empty array.
this is the function:
$(document).ready(function () {
$('input[type="checkbox"]').change(function () {
var mycheck = new Array();
if ($(this).is(':checked')) {
$("#line-checkbox-1:checked").each(function () {
mycheck.push($(this).val());//aggiungo value del checked
});
alert(mycheck)
} else {
var itemtoRemove = $(this);
mycheck.splice($.inArray(itemtoRemove, mycheck), 1); //rimuovo il value del dechecked
alert(mycheck);
}
});
This is HTML of the checkbox:
<div class="col-lg-3">
<input tabindex="17" id="line-checkbox-1" type="checkbox" name="servizi" value="3">
</div>
Try This Simple Script, this works for you:
HTML
<input type="checkbox" name="options[]" value="1" />
<input type="checkbox" name="options[]" value="2" />
<input type="checkbox" name="options[]" value="3" />
<input type="checkbox" name="options[]" value="4" />
<input type="checkbox" name="options[]" value="5" />
JQUERY
$(document).ready(function ()
{
$('input[type="checkbox"]').change(function ()
{
var arr = $.map($('input:checkbox:checked'), function(e,i) {
return +e.value;
});
alert(arr);
});
});
Its probably because you are using id to reference the checkboxes and since you are creating the array from scratch everytime user changes a checkbox. you should recheck the list everytime a checkbox is changed. That means you dont need that if.( if($(this).is(":checked") )
$('.checkboxes input[type="checkbox"]').change(function () {
var mycheck = new Array();
$(".checkboxes input[type='checkbox']:checked").each(function () {
if ($(this).is(':checked')) {
mycheck.push($(this).attr("id") + ": is " + $(this).val()); //aggiungo value del checked
}
});
alert(mycheck);
});
here is a fiddle if i understand correctly what you are trying to do

Categories