Set multi select options from stored localstorage values - javascript

I am trying to set multiple select options to selected, based on the corresponding localstorage value.
Storing the values in an array in localstorage is working, but I need help selecting the options in a form based on these values..
The values in localstorage are collected from checkboxes like so:
jQuery(document).ready(function(){
var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {},
checkboxes = jQuery(".add-selectie :checkbox");
checkboxes.on("change", function(){
checkboxes.each(function(){
checkboxValues[this.id] = this.checked;
});
localStorage.setItem("checkboxValues", JSON.stringify(checkboxValues));
});
jQuery.each(checkboxValues, function(key, value) {
jQuery('#' + key).prop('checked', value);
});
});
This saves the values in an array with the key "checkboxValues" in localstorage like so:
{"value1":true,"value2":true,"value3":false}
But how do I pre populate select options in a form if the value is found in localstorage AND set to true?
I made this pen containing all above code + a demo form. Any help would be greatly appreciated!

The code below should give you snippets to update selected state of option elements by reading values from localStorage.
Please note that there is a security issue in using localStorage in stackoverflow execution context so
I created a custom singleton/static class CustomLocalStorage having similar methods.
Additionally I've used a complete object OptionValueObject to back
the properties of checkbox and select elements.
var CustomLocalStorage = (function() {
var items = {};
function getItem(itemKey) {
for (var _itemKey in items) {
if (_itemKey === itemKey) {
return JSON.parse(items[itemKey]);
}
}
return null;
}
function setItem(itemKey, itemValue) {
items[itemKey] = JSON.stringify(itemValue);
}
return {
getItem: getItem,
setItem: setItem
}
})();
function OptionValueObject(id, label, value) {
this.id = id; // Used to identify checkboxes
this.label = label; // Not used in this example
this.value = value; // To bind it to select > option > value property
this.checked = true; // To bind it to checkbox > checked property
}
$(document).ready(function() {
function initialize() {
initializeData();
initializeUi();
}
function initializeData() {
var optionValueObjects = [];
optionValueObjects.push(new OptionValueObject(1, 'Label of option 1', 'value1'));
optionValueObjects.push(new OptionValueObject(2, 'Label of option 2', 'value2'));
optionValueObjects.push(new OptionValueObject(3, 'Label of option 3', 'value3'));
CustomLocalStorage.setItem('options', optionValueObjects);
}
function initializeUi() {
var optionValueObjects = CustomLocalStorage.getItem('options');
for (var i = 0; i < optionValueObjects.length; i++) {
var optionValueObject = optionValueObjects[i];
var id = optionValueObject.id;
// Checkbox: Identify element and set UI related property
var checkboxElement = $('#checkbox' + id);
checkboxElement.prop('checked', optionValueObject.checked);
console.log(optionValueObject.value);
// Option: Identify element and set UI related property
var optionElement = $("#optionsSelect > option[value='"+ optionValueObject.value +"']");
optionElement.prop('selected', optionValueObject.checked);
}
}
function handleEvents() {
function checkboxChangeHandler() {
// Get the object, update the checked property and save it back
// 1. Get the object
var id = $(this).prop('id');
var optionValueObjects = CustomLocalStorage.getItem('options');
var optionValueObject = optionValueObjects.filter(function(optionValueObject) {
if (('checkbox' + optionValueObject.id) === id) {
return optionValueObject;
}
})[0];
// 2. Update the checked property
var checked = $(this).prop('checked');
optionValueObject.checked = checked;
// Bind the checked property to options selected property
var optionElement = $("#optionsSelect > option[value='"+ optionValueObject.value +"']");
optionElement.prop('selected', optionValueObject.checked);
// 3. Save it back
CustomLocalStorage.setItem('options', optionValueObjects);
}
$('#checkbox1').change(checkboxChangeHandler);
$('#checkbox2').change(checkboxChangeHandler);
$('#checkbox3').change(checkboxChangeHandler);
}
initialize();
handleEvents();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="add-selectie">
<input id="checkbox1" class="selector" type="checkbox"><label for="checkbox1">Value 1</label>
<input id="checkbox2" class="selector" type="checkbox"><label for="checkbox2">Value 2</label>
<input id="checkbox3" class="selector" type="checkbox"><label for="checkbox3">Value 3</label>
</div>
<form>
<select id="optionsSelect" multiple="multiple">
<option value="value1">Value 1</option>
<option value="value2">Value 2</option>
<option value="value3">Value 3</option>
</select>
</form>

Related

Conditional removal of dropdown options based on checkbox selections

I've created a jsfiddle for this question, here: http://jsfiddle.net/navyjax2/9xpbyodq/
HTML
<span title="Fruit" class="ms-RadioText">
<input id="groupType_0" type="checkbox" checked="checked"/>
<label>Fruit</label>
</span><br>
<span title="Pies" class="ms-RadioText">
<input id="groupType_1" type="checkbox" />
<label>Pies</label>
</span>
<br><br>
<select id="Use_d8ffe43">
<option value="Apples">Apples</option>
<option value="Grapes">Grapes</option>
<option value="Both">Both</option>
</select><BR><BR>
JavaScript
$(document).ready(function () {
var whatSelected = new Array();
var piesOnly = false;
whatSelected.push('fruit'); // initial preset
var groupTypeField = $('input[id*="groupType"]');
groupTypeField.on('change', function () {
//alert(this.id);
var thisId = this.id.split('groupType_')[1];
//alert(thisId);
var thisChecked = this.checked;
var key = "";
if (thisId == 0)
key = "fruit";
else
key = "pies";
//alert(key);
if (whatSelected.indexOf(key) == -1 && thisChecked) {
whatSelected.push(key);
//alert('push: ' + key);
}
if (whatSelected.indexOf(key) != -1 && !thisChecked) {
//alert('pull: ' + key);
var index = whatSelected.indexOf(key);
//alert('index: ' + index);
if (index != -1) {
whatSelected.splice(index, 1);
//alert('pulled ' + key);
}
}
alert('after alteration: ' + whatSelected);
if (whatSelected.indexOf('pies') != -1) { // Pies checked
if (whatSelected.indexOf('fruit') != -1) { // Fruit checked, so not Pies only
piesOnly = false;
// Add "Grapes" and "Both" back, if gone
var exists = false;
$('select[id*="Use"] option').each(function () {
if (this.value == "Grapes") {
exists = true;
}
});
if (!exists) {
alert('added');
$('select[id*="Use"]').append('<option val="Grapes">Grapes</option>');
$('select[id*="Use"]').append('<option val="Both">Both</option>');
}
} else { // Fruit not checked
piesOnly = true;
// Remove Grapes and Both from dropdown
$('select[id*="Use"]').find('option[value="Grapes"]').remove(); $('select[id*="Use"]').find('option[value="Both"]').remove();
alert('removed');
}
} else { // Pies not checked
if (whatSelected.indexOf('fruit') != -1) { // Fruit checked, so not pies only
piesOnly = false;
} else {// nothing selected, revert to Fruit
alert('Must select an option.');
$('span[title*="Fruit"]').children(0).prop('checked', true);
$('span[title*="Pies"]').children(0).prop('checked', false);
piesOnly = false;
whatSelected.push('fruit'); // add it back
}
// Add "Grapes" and "Both" back to dropdown, if gone
var exists = false;
$('select[id*="Use"] option').each(function () {
if (this.value == "Grapes") {
exists = true;
}
});
if (!exists) {
alert('added');
$('select[id*="Use"]').append('<option value="Grapes">Grapes</option>');
$('select[id*="Use"]').append('<option value="Both">Both</option>');
}
}
});
});
Say I have 2 checkboxes, Fruit and Pies.
Say I have a dropdown, options: Apples, Grapes, Both
So if "Fruit" is selected, I expect all options to appear in the dropdown.
If "Pies" is selected, I only want "Apples", since who ever heard of a "Grape" pie? (or pie with "Both"?)
Fruit is the default selection, and at least one checkbox must be selected at all times. I have an array, "whatSelected", that tracks what checkboxes have been selected.
My code works to remove "Grapes" and "Both" from the dropdown if I select "Pies" and unselect "Fruit". (leaves "Apples" in the dropdown)
If I then re-select "Fruit", the options are all added back, correctly, through code I use to re-append the options using jQuery.
My issue is then, if I unselect "Fruit", it then DOES NOT remove "Grapes" and "Both", which are my appended options, on the dropdown. How can I remove these appended options? Thanks.
Actually I found my bug.... I have to do the appending in two places -- once if Fruit and Pies are selected, and another place, when Pie is not selected, but Fruit is. In one of the locations, I had...
$('select[id*="Use"]').append('<option val="Grapes">Grapes</option>');
$('select[id*="Use"]').append('<option val="Both">Both</option>');
Instead of val, I needed to use value. This solved my problem.
Rather than leave my jsfiddle broken, I updated it with this fix. But the code above is the original.
I thought about deleting this question, but thought there could be a lot of benefit to the coding community if I left this, since a lot of what is here are things often asked and could drive someone a little nutty on how to implement some of the things I did, here.

Get previous value of dropdown after onchange event jQuery

How do I get the previous value of my AUTO-Generated dropdown menu after an onchange event? Example
<select class="form-control" name="Diabetes_UK_3147" id="Diabetes_UK_3147" onchange="return verifyUpdateResponseGross(this);">
<option value="Yes">Yes</option>
<option value="Possibly">Possibly</option>
<option value="">N/A</option>
</select>
and I have this function
function verifyUpdateResponseGross(val)
{
var updated_response = val.value;
var colheader = val.name
var before_gross = $('#new_gross').val();
$.ajax({
url: "qa/api/crm/getquestion",
type: 'GET',
data: {'colheader':colheader},
success: function(result){
// var costperlead = result;
// if(updated_response != "")
// {
// var new_gross_amount = parseFloat(before_gross) + parseFloat(costperlead);
// $('#new_gross').val(new_gross_amount);
// }
// else
// {
// var new_gross_amount = parseFloat(before_gross) - parseFloat(costperlead);
// $('#new_gross').val(new_gross_amount);
// }
// console.log(costperlead);
}});
}
The reason I want to get the previous value is I need a checking that if the dropdown value is empty (N/A) then I need to perform some operation and if the value is not empty then I need perform another operation, But when the value gis not empty but the same from the previous value, then do nothing.
Those operation are those in comments. Thanks
UPDATE The id and name is autogenerated. That's why I have a
onchange="return verifyUpdateResponseGross(this);"
This will handle the change and do necessary operation.
This is it is autogenerated
Best way to do it by jquery :
$(document).ready(function(){
var previous;
$("#Diabetes_UK_3147").on("focus click",function () {
previous = this.value; // Old vaue
}).change(function() {
var value = this.value; // New Value
$('span').text('Old Value : '+previous+' New Value : '+value)
});
})
here the fiddle http://jsfiddle.net/Laa2hL3b/
Edited : in auto-Generated dropdown you can add a custom class for example "myselectbox"
<select class="form-control myselectbox"
and make change here
$(".myselectbox").on(/* other code remain same */
Use data to store the data instead a global variable:
$("#Diabetes_UK_3147").on("focus",function(){
$(this).data('previous',$(this).val());
}
Then you can access previous value by $("#Diabetes_UK_3147").data('previous');
jQuery data
Use data-* as below. Also, remove the inline event handler onchange="return verifyUpdateResponseGross(this);" and do it the unobtrusive way.
var $select = $("#Diabetes_UK_3147");
$select.data("previous-val", $select.val());
$select.on("change", function() {
var current_value = $(this).val();
if (current_value == "") {
//Do stuff when empty
} else if ( current_value != $(this).data("previousVal") && current_value != "" ) {
//Do stuff when not empty and current value != previous value
}
});
var $select = $("#my-select");
$select.data("prevVal", $select.val()).data("currVal", $select.val()).on("change", function () {
var $this = $(this);
$this.data("prevVal", $this.data("currVal")).data("currVal", $this.val());
// do your staff here. Previous value is available in $this.data("prevVal")
});

Change Javascript function from checkbox to select

I have a function that based on a checkbox id determines a price value. This works fine except I need to change the checkbox to a select. I tried to change the line:
if(peo14.checked==true)
To this:
if(peo14.select==Yes)
This did not work...how do I alter this to a Yes/No select?
function peoPrice()
{
var peoPrice=0;
//Get a reference to the form id="quicksheet"
var theForm = document.forms["quicksheet"];
//Get a reference to the checkbox id
var peo14 = theForm.elements["peo14"];
//If they checked the box set peoPrice to value
if(peo14.checked==true)
{
peoPrice=199;
}
//finally we return the peoPrice
return peoPrice;
}
You have to use the .options property and choose the selected index, then get the value of that index.
if (peo14.options[ peo14.selectedIndex ].value === 'Yes') {
peoPrice = 199;
}
Select Box
<select id="peo14" name='peo14' >
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
function peoPrice()
{
var peoPrice=0;
var e = document.getElementById("peo14");
var peo14val = e.options[e.selectedIndex].value;
if(peo14val=="Yes")
{
peoPrice=199;
}
//finally we return the peoPrice
return peoPrice;
}

How do i manipulate select box using jquery?

I have some select boxes like the following:
<select id="my_box1" rel="cal_10">
<option value="A"></option>
</select>
<select id="my_box2" rel="cal_10.50">
<option value="A"></option>
</select>
....
<select id="my_boxn">
<option value="B"></option>
</select>
On changing, I want to add the related value (that is 10 and 10.50) only when the select boxes has the same option value.
For Example: if the first and second select box has option value as A, then I want to add it.
How can I do this using jQuery?
Well, I really can't tell exactly what you're asking, so I'll just guess.
I'm guessing that when a select element receives a change event, we should find all other selects where the selected value is the same, and sum the numeric portion of the rel attribute.
If so, you can do this:
var boxes = $('select[id^="my_box"]');
boxes.on('change', function() {
var n = 0,
val = this.value;
boxes.each(function() {
if( this.value === val ) {
n += +$(this).attr('rel').replace('cal_','');
}
});
alert( n );
});
If you're using a version of jQuery older than 1.7, then use boxes.bind instead of boxes.on.
Something like this, I believe:
$(function() {
$('select#my_box1, select#my_box2').bind('change', function() {
if ($('select#my_box1').val() == $('select#my_box2').val())
$('select#my_box2').append('<option value="10">10</option><option value="10.50">10.50</option>');
else $('select#my_box2').find('option[value="10"], option[value="10.50"]').remove();
});
});
I tried by below code,
$('select').change(function(){
var totalWeight = 0;
var post_array = [];
var actual_val = value;
//alert(actual_val);
var x=0;
$("select").each(function(index, selectedObj) {
current = $(this).val();
var combined = $(this).attr('rel');
if(combined!=undefined)
{
combined = combined.split("_");
var is_combined = combined[0];
var combined_pid = combined[1];
if(actual_val == current && is_combined == "cal"){
post_array[x++] = combined_pid ;
totalWeight+=parseFloat(combined_pid);
}
}
});
alert(totalWeight);
});
I will get my total value in totalWeight

Add <select> options based on the value of a text input

How I can add options to a select field based on the value of a text input?
This is my input text:
<input type="text" id="amount" size="30" />
This is my element I want to add to:
<span id="span_combo">
<select name="foo" id="combo">
<option value="1">1</option>
<option value="2">2</option>
</select>
</span>
This is my current JS:
$("#amount").keyup(function(){
var flag;
$("#combo").show("slow");
var a = $("#amount").val();
if(a==""){
$("#span_combo select").remove(true);
}
var i;
for(i=1;i<=a-1;i++){
$("#span_combo").append($("#span_combo select").first().clone(true));
}
});
Something like this should do it
Live demo here : http://jsfiddle.net/NdpuM/1/
$("#amount").keyup(function(){
var $combo = $('#combo');
$combo.html('');
var value = parseInt($('#amount').val(), 10);
for (i = 1; i <= value; i++) {
var $option = $('<option>').val(i).html(i);
$combo.append($option);
}
});
Basically, clear the select box everytime there is a keydown and repopulate it. You could optimize this more by adding a few checks to see whether it's the same value
If you want to rebuild the entire array:
$("#amount").keyup(function(){
$("#combo").show("slow");
var a = $("#amount").val();
if(a==""){
$("#span_combo select").remove(true);
}
$('#combo').empty();
for(var i=1;i<=a-1;i++){
$('<option />').attr('value', i)
.text(i)
.appendTo($('#combo'));
}
});
I think this could work:
$("#amount").keyup(function() {
var current = $("#combo option").length;
if(current < $(this).val()) {
for(var i = current + 1;i<=$(this).val();i++) {
$("#combo").append('<option value="'+i+'">'+i+'</option>');
}
} else {
for(var i=(parseInt($(this).val(),10)+1);i<=current;i++) {
$('#combo option[value="'+i+'"]').remove();
}
}
});
You might want to add input verification to this function, but it does what you want if you use it right.
EDIT: Just to clarify, this code doesn't clear the whole select box on every keyup event, it just adds new options or removes the last ones to get the specified amount of values.

Categories

Resources