Helo guys, I've been working for my project for several months.
Now I'm trying to fill my dropdown list named (drpIdCorsi), based on the selection of another dropdown list named (drpDocente).
This is how my JSON object is composed:
listaCorsi =
[
{nomeCorso: "some course name"},
{emailDocente: "some email"},
]
I've loaded with an AJAX request a JSON object (which is filled correctly).
Now I'm trying to navigate my JSON object and fill the dropdown list, but it doesn't work.
This is the first function:
var listaCorsi = selezionaCorsoDocenti();
var listaCorsiDDL = '';
$('#drpDocente').on('change',function()
{
docente = $('#drpDocente').val();
docente = docente.trim();
docente= docente.split("-")[0];//gets the email of the professor
console.log(listaCorsi);
console.log(docente);
console.log(listaCorsi);
if(!$.isArray(listaCorsi))
listaCorsi = [listaCorsi];
$.each(listaCorsi,function(key,value)
{
console.log(value);
if(docente == value.emailDocente)
listaCorsiDDL += '<option value="">' + value.nomeCorso + '</option>';
});
$('#drpIdCorsi').append(listaCorsiDDL);
}).change();
This is the function called above (It actually works, but I'm not able to fill the second dropdown list, cause it shows undefined as result or nothing in the second dropdown list)
function selezionaCorsoDocenti()
{
var listaCorsi = [{}];
$.get('selezionaCorsiPerDocente',function(responseJson)
{
if(responseJson != null)
{
var i = 0;
$.each(responseJson,function(key,value)
{
listaCorsi[i] = [{nomeCorso: value.NOME_CORSO}, {emailDocente: value.EMAIL}];
i = i + 1;
});
}
else
alert("AJAX FAILED");
});
return listaCorsi;
}
I'd like to fill the second dropdown list like this:
if(docente === value.EMAIL)
course += '<option value="">' + value.NOME_CORSO + '</option>
$('#drpIdCorsi').append(course);
The function selezionaCorsoDocenti() WORKS JUST FINE.
The problem is that the JSON object listaCorsi, when I iterative over that object with the $.each() prints undefined for a certain field of the object
Your main issue is in this line:
var listaCorsi = selezionaCorsoDocenti();
$.get('selezionaCorsiPerDocente',.... is an ajax call, so it's asynchronous. You need to wait in order to get the result.
Moreover, when a change happens you need to empty the dropdown. From:
$('#drpIdCorsi').append(listaCorsiDDL);
to:
$('#drpIdCorsi').empty().append(listaCorsiDDL);
function selezionaCorsoDocenti() {
var listaCorsi = [{}];
return $.get('https://gist.githubusercontent.com/gaetanoma/5f06d1dbd111ff6a7778cd6def6b1976/raw/037587e927ac297e1f4907364898ead22ed03a0d/selezionaCorsiPerDocente.json',function(responseJson) {
responseJson = JSON.parse(responseJson);
if(responseJson != null) {
var i = 0;
$.each(responseJson,function(key,value) {
listaCorsi[i] = [{nomeCorso: value.nomeCorso}, {emailDocente: value.EMAIL}];
i = i + 1;
});
}
});
}
selezionaCorsoDocenti().then(function(x) {
listaCorsi = JSON.parse(x);
$('#drpDocente').trigger('change');
});
$('#drpDocente').on('change',function(e) {
var listaCorsiDDL = '';
docente = $('#drpDocente').val();
docente = docente.trim();
docente= docente.split("-")[0];//gets the email of the professor
if(!$.isArray(listaCorsi))
listaCorsi = [listaCorsi];
$.each(listaCorsi,function(key,value) {
if(docente == value.emailDocente)
listaCorsiDDL += '<option value="">' + value.nomeCorso + '</option>';
});
$('#drpIdCorsi').empty().append(listaCorsiDDL);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="drpIdCorsi"></select>
<select id="drpDocente">
<option>docente1#mail.edu</option>
<option>docente2#mail.edu</option>
<option>docente3#mail.edu</option>
</select>
Related
I've tried lot's of solutions here before actually make this question but none of them has worked for me.
I've tried to use onclick handler, tried to get by input name, tried getElementId, tried elementClassName also i tried to loop them var i = 0, length = radios.length; i < length; i++ none has worked for me!
Logic
My radio buttons will append to view based on ajax action
I select any of this radio buttons
And i want get values of this selected radio button
Code
This is how my radios append I made it short to be clean and easy to read
success:function(data) {
$('.shipoptions').empty();
$('.shipoptionstitle').empty();
$('.shipoptionstitle').append('<h6>Select your preferred method</h6>');
$.each(data.data, function(key, value) {
$.each(value.costs, function(key2, value2) {
$.each(value2.cost, function(key3, value3) {
// number format
var number = value3['value'];
var nf = new Intl.NumberFormat('en-US', {
maximumFractionDigits:0,
minimumFractionDigits:0
});
var formattedNumber = nf.format(number);
// number format
$('.shipoptions').append('<ul class="list-form-inline"><li><label class="radio"><input type="radio" name="postchoose" data-code="'+value['code']+'" data-service="'+value2['service']+'" value="'+ value3['value'] +'"><span class="outer"><span class="inner"></span></span>'+ value['code'] + ' - ' + value2['service'] + ' - Rp ' + nf.format(number) + ' - ' + value3['etd'] +'</label></li></ul>');
});
});
});
} //success function ends here
Now I want to get selected radio button values of data-code ,
data-service and value
For the temporary please just help me to get those values in console, later I'll fix the printing part myself.
Any idea?
<input type="radio" name="postchoose" data-code="'DC11'" data-service="'DS22'" value="'V33">
var dataCode = $('input[name="postchoose"]:checked').data('code');
var dataService = $('input[name="postchoose"]:checked').data('service');
var selectedVal= $("input:radio[name=postchoose]:checked").val();
SOLVED
$(function() {
$(".shipoptions").on('change', function(){
var radioValue = $("input[name='postchoose']:checked");
if(radioValue){
var val = radioValue.val();
var code = radioValue.data('code');
var service = radioValue.data('service');
alert("Your are a - " + code + "- " +service+ "- " +val);
}
});
});
I needed to get a higher class of my radio buttons .shipoptions
Try this jQuery Method.
$("input[type='radio']").click(function() {
var radioValue = $("input[name='postchoose']:checked").val();
var dataCode = $("input[name='postchoose']:checked").attr('data-code');
var dataService = $("input[name='gender']:checked").attr('data-service');
console.log(dataCode);
console.log(dataService);
console.log(radioValue);
});
I have a Contact Form that utilizes Google Scripts. It successfully sends the email and formats it decently to my inbox, but there are 2 problems:
-I need it so that IF var key is equal to 'Action', then do not display it in the email it sends. Because right now, "Action send_message" is getting included in the email and I don't like that.
For this, I have unsuccessfully tried things like:
for (var idx in order) {
var key = order[idx];
//Skip this entry into the email output if it is the Action
if( key === 'Action') {
continue
}
It seems to not react to this code at all.
-I also need it so that if a city is selected, e.g. Alachua, that the email says 'Alachua' instead of 'Florida_Alachua'. But I can't add a NAME to an option since apparently options don't have that property. I also can't do the quick fix of changing the VALUE of the <option> to resolve this step, because of other code I have that conflicts with this route.
Google Scripts Code:
/******************************************************************************
* This tutorial is based on the work of Martin Hawksey twitter.com/mhawksey *
* But has been simplified and cleaned up to make it more beginner friendly *
* All credit still goes to Martin and any issues/complaints/questions to me. *
******************************************************************************/
// if you want to store your email server-side (hidden), uncomment the next line
var TO_ADDRESS = "myemail#email.com";
// spit out all the keys/values from the form in HTML for email
// uses an array of keys if provided or the object to determine field order
function formatMailBody(obj, order) {
var result = "";
if (!order) {
order = Object.keys(obj);
}
// loop over all keys in the ordered form data
for (var idx in order) {
var key = order[idx];
result += "<h4 style='text-transform: capitalize; margin-bottom: 0'>" + key + "</h4><div>" + sanitizeInput(obj[key]) + "</div>";
// for every key, concatenate an `<h4 />`/`<div />` pairing of the key name and its value,
// and append it to the `result` string created at the start.
}
return result; // once the looping is done, `result` will be one long string to put in the email body
}
// sanitize content from the user - trust no one
// ref: https://developers.google.com/apps-script/reference/html/html-output#appendUntrusted(String)
function sanitizeInput(rawInput) {
var placeholder = HtmlService.createHtmlOutput(" ");
placeholder.appendUntrusted(rawInput);
return placeholder.getContent();
}
function doPost(e) {
try {
Logger.log(e); // the Google Script version of console.log see: Class Logger
record_data(e);
// shorter name for form data
var mailData = e.parameters;
// names and order of form elements (if set)
var orderParameter = e.parameters.formDataNameOrder;
var dataOrder;
if (orderParameter) {
dataOrder = JSON.parse(orderParameter);
}
// determine recepient of the email
// if you have your email uncommented above, it uses that `TO_ADDRESS`
// otherwise, it defaults to the email provided by the form's data attribute
var sendEmailTo = (typeof TO_ADDRESS !== "undefined") ? TO_ADDRESS : mailData.formGoogleSendEmail;
// send email if to address is set
if (sendEmailTo) {
MailApp.sendEmail({
to: String(sendEmailTo),
subject: "Contact form submitted",
// replyTo: String(mailData.email), // This is optional and reliant on your form actually collecting a field named `email`
htmlBody: formatMailBody(mailData, dataOrder)
});
}
return ContentService // return json success results
.createTextOutput(
JSON.stringify({"result":"success",
"data": JSON.stringify(e.parameters) }))
.setMimeType(ContentService.MimeType.JSON);
} catch(error) { // if error return this
Logger.log(error);
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": error}))
.setMimeType(ContentService.MimeType.JSON);
}
}
/**
* record_data inserts the data received from the html form submission
* e is the data received from the POST
*/
function record_data(e) {
var lock = LockService.getDocumentLock();
lock.waitLock(30000); // hold off up to 30 sec to avoid concurrent writing
try {
Logger.log(JSON.stringify(e)); // log the POST data in case we need to debug it
// select the 'responses' sheet by default
var doc = SpreadsheetApp.getActiveSpreadsheet();
var sheetName = e.parameters.formGoogleSheetName || "responses";
var sheet = doc.getSheetByName(sheetName);
var oldHeader = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
var newHeader = oldHeader.slice();
var fieldsFromForm = getDataColumns(e.parameters);
var row = [new Date()]; // first element in the row should always be a timestamp
// loop through the header columns
for (var i = 1; i < oldHeader.length; i++) { // start at 1 to avoid Timestamp column
var field = oldHeader[i];
var output = getFieldFromData(field, e.parameters);
row.push(output);
// mark as stored by removing from form fields
var formIndex = fieldsFromForm.indexOf(field);
if (formIndex > -1) {
fieldsFromForm.splice(formIndex, 1);
}
}
// set any new fields in our form
for (var i = 0; i < fieldsFromForm.length; i++) {
var field = fieldsFromForm[i];
var output = getFieldFromData(field, e.parameters);
row.push(output);
newHeader.push(field);
}
// more efficient to set values as [][] array than individually
var nextRow = sheet.getLastRow() + 1; // get next row
sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
// update header row with any new data
if (newHeader.length > oldHeader.length) {
sheet.getRange(1, 1, 1, newHeader.length).setValues([newHeader]);
}
}
catch(error) {
Logger.log(error);
}
finally {
lock.releaseLock();
return;
}
}
function getDataColumns(data) {
return Object.keys(data).filter(function(column) {
return !(column === 'formDataNameOrder' || column === 'formGoogleSheetName' || column === 'formGoogleSendEmail' || column === 'honeypot');
});
}
function getFieldFromData(field, data) {
var values = data[field] || '';
var output = values.join ? values.join(', ') : values;
return output;
}
Contact Form HTML
<section id="contact-form">
<form id="gform"
class="contact-form" method="post"
action="(Google Scripts URL)"
enctype="text/plain">
<p>
<label for="name">Your Name <font face="Arial" color="red">*</font></label>
<input type="text" style="height:35px;" class="heighttext required" name="name" id="name" class="required" title="* Please provide your name">
</p>
<p>
<label>Your Location <font face="Arial" color="red">*</font></label>
<select name="Location" id="column_select" style="height:35px;" class="required" title=" * Please provide your location">
<option selected value="col00">-- State --</option>
<option value="Alabama">Alabama</option>
<option value="California">California</option>
<option value="Florida">Florida</option>
</select>
<select name="City" id="layout_select" style="height:35px;">
<option disabled selected value="Florida">-- City --</option>
<option name="Alachua" value="Florida_Alachua">Alachua</option>
<option name="Alford" value="Florida_Alford">Alford</option>
</select>
</p>
<p>
<input type="submit" value="Send Message" id="submit" class="pp-btn special">
<img src="images/ajax-loader.gif" id="contact-loader" alt="Loading...">
<input type="hidden" name="action" value="send_message">
</p>
</form>
</section><!-- #contact-form -->
Form Handler Javascript
(function() {
function validEmail(email) { // see:
var re = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
return re.test(email);
}
function validateHuman(honeypot) {
if (honeypot) { //if hidden form filled up
console.log("Robot Detected!");
return true;
} else {
console.log("Welcome Human!");
}
}
// get all data in form and return object
function getFormData() {
var form = document.getElementById("gform");
var elements = form.elements;
var fields = Object.keys(elements).filter(function(k) {
return (elements[k].name !== "honeypot");
}).map(function(k) {
if(elements[k].name !== undefined) {
return elements[k].name;
// special case for Edge's html collection
}else if(elements[k].length > 0){
return elements[k].item(0).name;
}
}).filter(function(item, pos, self) {
return self.indexOf(item) == pos && item;
});
var formData = {};
fields.forEach(function(name){
var element = elements[name];
// singular form elements just have one value
formData[name] = element.value;
// when our element has multiple items, get their values
if (element.length) {
var data = [];
for (var i = 0; i < element.length; i++) {
var item = element.item(i);
if (item.checked || item.selected) {
data.push(item.value);
}
}
formData[name] = data.join(', ');
}
});
// add form-specific values into the data
formData.formDataNameOrder = JSON.stringify(fields);
formData.formGoogleSheetName = form.dataset.sheet || "responses"; // default sheet name
formData.formGoogleSendEmail = form.dataset.email || ""; // no email by default
console.log(formData);
return formData;
}
function handleFormSubmit(event) { // handles form submit without any jquery
event.preventDefault(); // we are submitting via xhr below
var data = getFormData(); // get the values submitted in the form
/* OPTION: Remove this comment to enable SPAM prevention, see README.md
if (validateHuman(data.honeypot)) { //if form is filled, form will not be submitted
return false;
}
*/
if( data.email && !validEmail(data.email) ) { // if email is not valid show error
var invalidEmail = document.getElementById("email-invalid");
if (invalidEmail) {
invalidEmail.style.display = "block";
return false;
}
} else {
disableAllButtons(event.target);
var url = event.target.action; //
var xhr = new XMLHttpRequest();
xhr.open('POST', url);
// xhr.withCredentials = true;
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
console.log( xhr.status, xhr.statusText )
console.log(xhr.responseText);
//document.getElementById("gform").style.display = "none"; // hide form
/*
var thankYouMessage = document.getElementById("thankyou_message");
if (thankYouMessage) {
thankYouMessage.style.display = "block";
}
*/
return;
};
// url encode form data for sending as post data
var encoded = Object.keys(data).map(function(k) {
return encodeURIComponent(k) + "=" + encodeURIComponent(data[k])
}).join('&')
xhr.send(encoded);
}
}
function loaded() {
console.log("Contact form submission handler loaded successfully.");
// bind to the submit event of our form
var form = document.getElementById("gform");
form.addEventListener("submit", handleFormSubmit, false);
};
document.addEventListener("DOMContentLoaded", loaded, false);
function disableAllButtons(form) {
var buttons = form.querySelectorAll("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].disabled = true;
}
}
})();
finally, this is the extra code that would break if I simply tried changing the value of option to, e.g., 'Alachua' instead of 'Flordia_Alachua'. https://jsfiddle.net/hmatt843/504dgmqy/19/
Thanks for any and all help.
Try console.log(key) before if( key === 'Action'). I think you'll find that key never equals 'Action', exactly. Looks like you'll need if( key === 'action'), instead.
If you wish to remove part of string value, try the replace method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
It also looks like you're trying to work with elements[k].name when you mean to be working with elements[k].value.
I believe your code should look something like...
function(k) {
if(elements[k].value !== undefined) {
return elements[k].value.replace('Florida_', '');
// special case for Edge's html collection
} else if(elements[k].length > 0){
return elements[k].item(0).value.replace('Florida_', '');
}
}
... or something to that effect.
In the future, you may want to make it easier for folks trying to help you by posting only the portions of code your having trouble with, and breaking your questions into different posts. A lot to sift through up there.
Hope this helped.
The split() method splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.
Var splitValue = elements[k].item(0).value.split("");
splitValue[1] will give you a string of characters after the delimeter () in this case.
I have a form that has a hidden text input that gets the user id called user_number_id and depending on the value the dropdown called departamento_drop gets an options filtered to retorno1. The problem is that when I open this form to edit something inside it, the selected option of this dropdown changes automatically and changes the real selected value. How can I keep the selected value selected and make sure the filter can understand that and have to respect it?
$("#user_number_id").val(function(){
var selecionado = $(this).val();
jQuery.get("<?php echo base_url().'departamentos/filter_departamento/'; ?>"+selecionado,
function(retorno1){
var ret1 = '<option value="0">------ N/A ------</option>' + retorno1;
var ret2 = retorno1 + '<option value="0">------ N/A ------</option>';
if($("#departamento_drop option:selected").val() > '0'){
jQuery("#departamento_drop").html(ret2);
}else{
jQuery("#departamento_drop").html(ret1);
}
});
});
after 9 hours of work on it, I done this solution but still I need to find how to remove the selected option from retorno1 to not be duplicated, and for sure if there is any other idea better please share. thank you
$("#user_number_id").val(function(){
var selecionado = $(this).val();
jQuery.get("<?php echo base_url().'departamentos/filter_departamento/'; ?>"+selecionado,
function(retorno1){
var i = 0;
var pre = retorno1 + '<option value="0">------ N/A ------</option>';
var count = $($.parseHTML(retorno1)).filter('option').length;
var dep_dr = $("#departamento_drop option:selected").val();
for(i=0; i < count; i++){
var val_drop = $($.parseHTML(retorno1)).filter("option[value*='" + i + "']").val();
var text_drop = $($.parseHTML(retorno1)).filter("option[value*='" + i + "']").text();
if (val_drop == dep_dr){
jQuery("#departamento_drop").html("<option value ='"+val_drop+"' selected='selected'>"+text_drop+"</option>"+pre);
}else if(dep_dr == '0'){
jQuery("#departamento_drop").html("<option value ='"+dep_dr+"' selected='selected'>------ N/A ------</option>"+pre);
}
}
});
});
I am having an issue where the current state of the checkbox is not being saved. I am new to this and any help would be appreciated. Here's the jQuery code that is partially working.
var userCityList = [];
$("#checkboxes").unbind('change').bind('change', function (event) {
var stateVal = $(':selected', $('#ResidentialLocationStateList')).val();
var cityID = $(event.target)[0].id;//stores city id
var cityVal = $(event.target)[0].value;//stores city value
if ($('#' + cityID).is(':checked')) {
if (userCityList.length < 5) {
userCityList.push(cityID);
}
else {
$('#' + cityID).prop('checked', false);
alert("5 cities have been selected");
return;
}
}//end if
if (!($("#" + cityID).is(':checked'))) {
userCityList.pop();
}
//console.log(userCityList);
});
LOGIC
When the user selects a state, a set of cities in checkboxes appear. When a user clicks a checkbox, that particular city is stored in the userCityList array. When the user clicks it again, it deletes it from the array. However, if the user changes the state, those cities are no longer checked, which does not allow one to delete it from the array, if needed.
Any suggestions?
HTML code
<div class="panel-body">
<p>Select upto 5 state/city combinations</p>
<div class="col-xs-3 no-pad-left less-width">
#*<p>Select upto 5 state/city combinations</p>*#
<select id="ResidentialLocationStateList" name="ResidentialLocationStateList" multiple></select>
</div>
<div class="col-xs-3" id="checkboxes">
</div>
</div>
UPDATE Here's the image that goes with this issue.
So when a few cities are selected and the user decides to change the state from the select element, those cities that were selected prior need to be saved.
UPDATE
Here's the AJAX code...
$("#ResidentialLocationStateList").change(function () {
url = "/ResidentialBuilding/getCityList?state=";
state = $("#ResidentialLocationStateList").val();
url = url + state;
//console.log(url);
$("#checkboxes").empty();
$.getJSON(url, function (data) {
//console.log(data);
$.each(data, function (index, value) {
//console.log(value.city);
id = value.city;
id = id.replace(/\s+/g, '');
valCity = value.city;
valCity = valCity.replace(/\s+/g, '');
$("#checkboxes").append('<input value="' + valCity + '"' + 'type=' + "'checkbox'" + 'id=' + id + '>' + value.city + '</input><br>');
});
});
});
If you're using a modern version of jQuery I would recommend using .off and .on and to use .off if you really have to.
lso the .pop() array method removes the last element but the element just clicked may not always be the one that was added last. And since, the check boxes are added dynamically, the following bind could be made at the very beginning of DOM ready and not necessarily in any event handler. Rather than give your checkboxes the same ID which leads to invalid HTML, use a class selector, .checkboxes.
Therefore, I would suggest the following code
var userCityList = [];
$(document).on("change", ".checkboxes", function() {
var stateVal = $('#ResidentialLocationStateList').val();
var cityID = this.id;//stores city id
var cityVal = this.value;//stores city value
var finalDiv = $('#final');
var tempDiv = $('#othertempdiv');
if( this.checked ) {
if( userCityList.length < 5 ) {
userCityList.push( cityID );
finalDiv.append( this );
} else {
$(this).prop('checked', false);
alert('5 cities have been selected');
}
} else {
var index = $.inArray( cityID, userCityList );
if( index > -1 ) {
userCityList.splice( index, 1 );
tempDiv.append( this );
}
}
});
Since you're -- per comments below -- replacing the selected cities each time you select a new state, you would have to have a second div which would hold all the selected cities. Un-checking any of the cities in this final div would move it back; if another state is selected, such a city would be lost.
<div id="final"></div>
Use a multidimensional array to store both state and city IDs, like userCityList [ stateVal ]:
var userCityList = [];
$("#checkboxes").unbind('change').bind('change', function (event) {
var stateVal = $(':selected', $('#ResidentialLocationStateList')).val();
var cityID = $(event.target)[0].id;//stores city id
var cityVal = $(event.target)[0].value;//stores city value
if ($('#' + cityID).is(':checked')) {
if (userCityList.length < 5) {
if(!userCityList[stateVal])userCityList[stateVal] = [];
userCityList[stateVal].push(cityID);
}
else {
$('#' + cityID).prop('checked', false);
alert("5 cities have been selected");
return;
}
}//end if
if (!($("#" + cityID).is(':checked'))) {
if(userCityList[stateVal]){
//Edited, now it can remove the city by its position (index)
var position = $.inArray(cityID, userCityList[stateVal]);
userCityList[stateVal].slice(position, 1);
}
}
});
So when you need to retrieve the checked cities for an state you can do just:
for(var i =0; i < userCityList[stateVal].length; i++){
console.log(userCityList[stateVal][i]);
}
UPDATE
The hard work is done. Now, in your ajax code, when you load a new set of checkboxes, you have to check if the checkbox was previously checked:
$("#ResidentialLocationStateList").change(function () {
url = "/ResidentialBuilding/getCityList?state=";
state = $("#ResidentialLocationStateList").val();
url = url + state;
//console.log(url);
$("#checkboxes").empty();
$.getJSON(url, function (data) {
//console.log(data);
$.each(data, function (index, value) {
//console.log(value.city);
id = value.city;
id = id.replace(/\s+/g, '');
valCity = value.city;
valCity = valCity.replace(/\s+/g, '');
$("#checkboxes").append('<input value="' + valCity + '"' + 'type=' + "'checkbox'" + 'id=' + id + '>' + value.city + '</input><br>');
//Let's check if this checkbox was previously checked
if($.inArray(id, userCityList[state])){
//if yes, let's check it again
$('#'+id).prop('checked', true);
}
});
});
});
Keep in mind that the userCityList variable must be global to store these values and you will loose your checkboxes memories if you refresh the page, of course.
I have a form which saves a users preferance in local storage, it can be seen in this fiddle or below.
With what I have so far there are 2 main problems.
On clicking the save button you are meant to empty the myStorage then append what you have just selected in there, so they can see the live result of what they have clicked. It only remembers if you re-run the fiddle.
My biggest problem is that what I have is great for select fields with one option but in this case the user can select multiple, so what do I need to add to it so that the user can save multiple values to local storage so next time they load the page there multiple selections will be saved?
<form name="Filter">
<select multiple="1" id="filter">
<option value="111">Andrew</option>
<option value="222">Bill</option>
<option value="333">Charles</option>
<option value="444">Dikembe</option>
<option value="555">Edward</option>
</select>
</form>
<div id="store">click to store</div>
<br>
<h3>People I have stored</h3>
<div id="myStorage"></div>
JS
var iSelectedTitle = localStorage.getItem('title');
var iSelectedVal = localStorage.getItem('value');
console.log("iSelectedTitle: " + iSelectedTitle);
console.log("iSelectedVal: " + iSelectedVal);
$("#filter option").each(function () {
if ($(this).val() == iSelectedVal) {
$(this).attr("selected", "selected");
}
});
$("#store").click(function () {
var mytitle = $("#filter option:selected").text();
var storedTitle = localStorage.setItem("title", mytitle);
console.log("mytitle: " + mytitle);
console.log("storedTitle: " + storedTitle);
var myValue = $("#filter option:selected").val();
var storedValue = localStorage.setItem("value", myValue);
console.log("myValue: " + myValue);
console.log("storedValue: " + storedValue);
if (iSelectedTitle != "undefined") {
$('#myStorage').empty().append(iSelectedTitle);
}
});
if (iSelectedTitle != "undefined") {
$('#myStorage').append(iSelectedTitle + ' - <a target= "_blank "href="http://www.example.com/' + iSelectedVal + '">View profile</a>');
}
You can add multiple options to an array using map of jQuery :
var optArray = $("#filter option:selected").map(function () {
return {
"title": this.innerHTML,
"value": this.value
}
}).get();
This will give you a nice array like this :
[
{ "title": "Andrew", "value": "111" },
{ "title": "Bill", "value": "222" },
{ "title": "Charles", "value": "333" }
]
For adding to localStorage :
$("#store").click(function () {
//get the selected options in the form of an array
var optArray = $("#filter option:selected").map(function () {
return {
"title": this.innerHTML,
"value": this.value
}
}).get();
console.log(optArray);
//set that to localStorage
localStorage["optArray"] = JSON.stringify(optArray);
//refresh myStorage
getFromStore();
});
For refreshing the myStorage container with your newly added people, you'll have to call this handler as the last event inside the `click event (above).
var getFromStore = function () {
//check if store values are null, if null, make store =[]
var store = [undefined, null].indexOf(localStorage["optArray"]) != -1 ? [] : JSON.parse(localStorage["optArray"]);
console.log(store);
//empty container before u put values
$('#myStorage').html('');
//check if store is empty
if (store.length != 0) {
//loop over store if it aint empty and append the content into myStorage div
for (var k in store) {
var str = '<div>' + store[k]["title"] + ' - <a target= "_blank" href="http://www.example.com/' + store[k]["value"] + '">View profile</a></div>';
console.log(store[k]);
$('#myStorage').append(str);
}
} else {
//do this if no data is found in localStorage
$("#myStorage").html("No people found in store");
}
}
Then, in DOM ready, call getFromStore to refresh myContainer on load of the page:
$(function() {
getFromStore();
})
Demo : http://jsfiddle.net/hungerpain/hqVGS/9/
EDIT
To select the checkboxes by default, add the folowing line in the getFromStore function :
$("[value=" + store[k]["value"] + "]","#filter").prop("selected", true); //find the option with the corresponding value and select it
Updated demo : http://jsfiddle.net/hungerpain/hqVGS/10/
You could save multiple values in an array,
var myValuesArr = ['one','two','three'];
The array would need to be serialized before it is saved to localStorage
var serialVals = JSON.stringify(myValuesArr);
localStorage.setItem('numbers',serialVals);
Likewise, the stored data will have to be unserialized after it is read back
var serialVals = localStorage.getItem('numbers');
var myValuesArr = JSON.parse(serialVals);