How to add multiple values to a key in local storage - javascript

Im trying to allow a user to select multiple select options that can be stored in local storage.
Trying to allow users to choose multiple select options that get saved and are displayed on screen.
html
<body>
<div class="custom_tunings">
<h1>Custom Tunings</h1>
<br>
<fieldset>
<legend>Add New Tunings</legend>
<div class="formBox">
<label for="">Tuning Name</label>
<input type="text" id="inpkey" placeholder="Insert Name"> <br>
</div>
<form class="" action="index.html" method="post">
<div class="formBox">
<select class="mynoteslist" id="inpvalue">
<option value="A1">A1</option>
<option value="B1">B1</option>
<option value="C1">C1</option>
<option value="D1">D1</option>
<option value="E1">E1</option>
<option value="F1">F1</option>
<option value="G1">G1</option>
</select>
</div>
<div class="formBox">
<select class="mynoteslist" id="inpvalue2">
<option value="A1">A1</option>
<option value="B1">B1</option>
<option value="C1">C1</option>
<option value="D1">D1</option>
<option value="E1">E1</option>
<option value="F1">F1</option>
<option value="G1">G1</option>
</select>
</div>
</form>
<button type="button" id="btninsert">Save Tuning </button>
<br>
</fieldset>
<fieldset>
<legend>My Tunings</legend>
<div id="isoutput"> </div>
</fieldset>
</div>
Im trying add multiple inpvalues to a key.
I cant seem to add another inpvalue as it seems to only accept the first value.
Im wondering if theres a simple way around this?
javascript
let inpkey = document.getElementById("inpkey");
let inpvalue=document.getElementById("inpvalue");
//let inpvalue2=document.getElementById("inpvalue2");
let btninsert = document.getElementById("btninsert");
let isoutput = document.getElementById("isoutput");
btninsert.onclick = function(){
let key = inpkey.value;
let value = inpvalue.value;
//let value2 = inpvalue.value;
console.log(key);
console.log(value);
//console.log(value2);
if(key && value) {
localStorage.setItem(key,value);
location.reload();
}
};
for(let i=0; i<localStorage.length; i++){
let key=localStorage.key(i);
let value=localStorage.getItem(key);
isoutput.innerHTML += `${key}: ${value} <br>` ;
}
the desired output would be something like this
Howver if i try to select different options it only takes the first value and applies them to all.

You need to check for the existence of a key and if found, append the new value to the existing value before saving.
if(key && value) {
// if the key exists
if(localStorage.getItem(key)){
// split the existing values into an array
let vals = localStorage.getItem(key).split(',');
// if the value has not already been added
if(! vals.includes(value)){
// add the value to the array
vals.push(value);
// sort the array
vals.sort();
// join the values into a delimeted string and store it
localStorage.setItem(key, vals.join(','));
}
}else{
// the key doesn't exist yet, add it and the new value
localStorage.setItem(key,value);
}
location.reload();
}
I made a working example of the above code here: https://jsfiddle.net/01rjn3cf/2/
EDIT: Based on your comments and added example of desired output, I see that you don't want a distinct list of values and that any value can be added to the list of previously selected values. In this case the solution is even easier..
if(key && value) {
// if the key exists
if(localStorage.getItem(key)){
// add this value onto the end of the existing string
localStorage.setItem(key, localStorage.getItem(key) + ', ' + value);
}else{
// the key doesn't exist yet, add it and the new value
localStorage.setItem(key,value);
}
location.reload();
}
EDIT:
I modified it as so to work as desired.
if(key && value) {
var content = value + ', ' + value2 + value3;
// if the key exists
if(localStorage.getItem(key)){
// add this value onto the end of the existing string
localStorage.setItem(key, content);
}else{
// the key doesn't exist yet, add it and the new value
localStorage.setItem(key, content);
}
location.reload();
}
};
for(var i=0; i<localStorage.length; i++){
var key=localStorage.key(i);
var value=localStorage.getItem(key);
isoutput.innerHTML += `${key}: ${value} <br>` ;
}

Once you have implemented #Drew's fix to store a list of items, you will need to supply all of the values of the selects.
Rather than
btninsert.onclick = function(){
let key = inpkey.value;
let value = inpvalue.value;
//let value2 = inpvalue.value;
...
You'll need all of the selects, and then pass each one into the localStorage part. Here I find all the select elements with class "mynoteslist", get their values, then filter out the empty ones
btninsert.onclick = function(){
let key = inpkey.value;
const inpValues = [...document.querySelectorAll("select.mynoteslist")]
.map({value} => value)
.filter(value => value);
if (inpValues.length) {
inpValues.forEach(v => storeLocally(key, v));
location.reload();
}
//...
Then #Drew's part wrapped in a function
function storeLocally(key, value) {
if(key && value) {
// if the key exists
if(localStorage.getItem(key)){
// split the existing values into an array
let vals = localStorage.getItem(key).split(',');
// if the value has not already been added
if(! vals.includes(value)){
// add the value to the array
vals.push(value);
// sort the array
vals.sort();
// join the values into a delimeted string and store it
localStorage.setItem(key, vals.join(','));
}
}else{
// the key doesn't exist yet, add it and the new value
localStorage.setItem(key,value);
}
}
}

Related

onClick event that checks if an array includes the element

I have an array of state which is controlled through a dropdown.
This is state held like:
const [finalselected, setfinalSelected] = useState([]);
When a submit button is clicked, I would like to confirm that an element does not already exist in the array, for example an individual cannot input "experience": "A similar role" 10 times into the array.
My current function does not stop additional elements coming if it is a duplicate:
const onSubmitFinalSelection = (val) => {
if (!finalselected.includes(selectedExperience)) {
//if finalselected does NOT include the element, then add in a new element
// setfinalSelected((prev) => [...prev, selectedExperience, inputfield]);
setfinalSelected((prevFinalSelection) => [
...prevFinalSelection,
{
//this is the dropdown
experience: selectedExperience,
//this is an input
inputfield,
},
]);
}
console.log(finalselected)
};
How would you re-write this?
Something like this? I don't think the includes function works with the selectedExperience as single parameter since the array contains objects.
const onSubmitFinalSelection = (val) => {
// If found, return
if (finalselected.some(x => x.experience === selectedExperience))
return;
setfinalSelected([...finalSelected, {
//this is the dropdown
experience: selectedExperience,
//this is an input
inputfield,
}])
console.log(finalsSlected)
};
Alerting if the element is already inside my array if not doing normal push.
let selectedValues = document.querySelector(".selectedValues");
let array = [];
function myFunction(option) {
option = option.value;
if (array.includes(option)) {
alert(option + " "+ "is already selected")
} else {
array.push(option);
}
selectedValues.textContent = array;
}
<textarea class="selectedValues" type="text"></textarea>
<select onchange="myFunction(this)" id="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>

Change hidden input field value according to select options

I am trying to write a script for changing the hidden input value according to selected options.
I have hindi data stored on a variable and I need to pick this hindi data according to english data selected in select feild. The select options are working fine so far, but I am unable to fectch the related hindi data.
var stateObject = {
"Bihar": {
"Begusarai": ["Bachhwara", "Bakhari", "Balia", "Barauni", "Begusarai", "Bhagwanpur", "Birpur", "Cheriya Bariyarpur", "Chhorahi", "Dandari", "Garhpura", "Khudabandpur", "Mansoorchak", "Matihani", "Nawkothi", "Sahebpur Kamal", "Samho Akha Kurha", "Teghra"],
},
}
var stateObjectHindi = {
"बिहार": {
"बेगूसराय": ["बछवारा", "बखरी", "बलिया", "बरौनी", "बेगुसराय", "भगवानपुर", "बीरपुर", "चेरिया बरियारपुर", "छौराही", "डंडारी", "गढ़पुरा", "खोदाबंदपुर", "मंसूरचक", "मटिहानी", "नावकोठी", "साहेबपुर कमाल", "साम्हो अखा कुरहा", "तेघरा"],
},
}
window.onload = function() {
var stateList = document.getElementById("stateList"),
stateListHindi = document.getElementById("stateListHindi"),
districtList = document.getElementById("districtList"),
districtListHindi = document.getElementById("districtListHindi"),
blockList = document.getElementById("blockList"),
blockListHindi = document.getElementById("blockListHindi");
for (var country in stateObject) {
stateList.options[stateList.options.length] = new Option(country, country);
}
stateList.onchange = function() {
districtList.length = 1; // remove all options bar first
blockList.length = 1; // remove all options bar first
if (this.selectedIndex < 1) return; // done
for (var state in stateObject[this.value]) {
districtList.options[districtList.options.length] = new Option(state, state);
}
}
stateList.onchange(); // reset in case page is reloaded
districtList.onchange = function() {
blockList.length = 1; // remove all options bar first
if (this.selectedIndex < 1) return; // done
var district = stateObject[stateList.value][this.value];
for (var i = 0; i < district.length; i++) {
blockList.options[blockList.options.length] = new Option(district[i], district[i]);
stateListHindi.value = this.value;
}
}
}
<select name="state" id="stateList">
<option value="" selected="selected">Select State</option>
</select>
<select name="district" id="districtList">
<option value="" selected="selected">Select District</option>
</select>
<select name="block" id="blockList">
<option value="" selected="selected">Select Block</option>
</select>
<br/> State in Hindi: <input type="hidden" class="stateListHindi" id="stateListHindi" name="stateListHindi" value="" /><br/> District in Hindi: <input type="hidden" class="districtListHindi" id="districtListHindi" name="districtListHindi" value="" /><br/>Block in Hindi: <input type="hidden" class="blockListHindi" id="blockListHindi" name="blockListHindi" value="" /><br/>
JSFiddle Demo
Your data structure is perhaps not too well-suited for what you want here. You need to find the corresponding property in both objects, for the first two levels, by their position - so you will have to extract the keys first, and use indexOf to locate them.
So for the state first of all, that would be
var selectedKeyIndex = Object.keys(stateObject).indexOf(this.value);
stateListHindi.value = Object.keys(stateObjectHindi)[selectedKeyIndex];
Extract the keys from the English object, and find the index of the property matching the current selection in there. Then use that index, to extract the corresponding property name from the Hindi object.
Now, for the district, you'll have to do the same thing, but for one more level:
var selectedKeyIndex = Object.keys(stateObject[stateList.value]).indexOf(this.value);
districtListHindi.value = Object.keys(stateObjectHindi[stateListHindi.value])[selectedKeyIndex];
And then for the Blocks, which are in an array, you can select directly by index,
var selectedKeyIndex = stateObject[stateList.value][districtList.value].indexOf(this.value);
blockListHindi.value = stateObjectHindi[stateListHindi.value][districtListHindi.value][selectedKeyIndex];
All of it put together here: https://jsfiddle.net/6g5ad4cz/.
(I made the hidden fields into normal text fields, so that the result can be visually checked straight away.)

how select multiple values from html drop down list with out holding ctrl button

i am trying to generate list from dropdown selected values using html and JavaScript, my code is working fine. but when i want to select multiple values its required to hold ctrl button. below is my form
<form action="#" method="post" id="demoForm" class="demoForm">
<fieldset>
<p>
<select name="demoSel[]" id="demoSel" size="4" multiple>
<option value="scroll">Scrolling Divs JavaScript</option>
<option value="tooltip">JavaScript Tooltips</option>
<option value="con_scroll">Continuous Scroller</option>
<option value="banner">Rotating Banner JavaScript</option>
<option value="random_img">Random Image PHP</option>
<option value="form_builder">PHP Form Generator</option>
<option value="table_class">PHP Table Class</option>
<option value="order_forms">PHP Order Forms</option>
</select>
<input type="submit" value="Submit" />
<!--<textarea name="display" id="display" placeholder="view select list value(s) onchange" cols="20" rows="4" readonly></textarea>-->
<div id="display"></div>
</p>
</fieldset>
</form>
then my javascript:
<script>
// arguments: reference to select list, callback function (optional)
function getSelectedOptions(sel, fn) {
var opts = [], opt;
// loop through options in select list
for (var i=0, len=sel.options.length; i<len; i++) {
opt = sel.options[i];
// check if selected
if ( opt.selected ) {
// add to array of option elements to return from this function
opts.push(opt);
// invoke optional callback function if provided
if (fn) {
fn(opt);
}
}
}
// return array containing references to selected option elements
return opts;
}
// example callback function (selected options passed one by one)
function callback(opt) {
// can access properties of opt, such as...
//alert( opt.value )
//alert( opt.text )
//alert( opt.form )
// display in textarea for this example
var display = document.getElementById('display');
display.innerHTML += opt.value + ', ';
}
// anonymous function onchange for select list with id demoSel
document.getElementById('demoSel').onchange = function(e) {
// get reference to display textarea
var display = document.getElementById('display');
display.innerHTML = ''; // reset
// callback fn handles selected options
getSelectedOptions(this, callback);
// remove ', ' at end of string
var str = display.innerHTML.slice(0, -2);
display.innerHTML = str;
};
document.getElementById('demoForm').onsubmit = function(e) {
// reference to select list using this keyword and form elements collection
// no callback function used this time
var opts = getSelectedOptions( this.elements['demoSel[]'] );
alert( 'The number of options selected is: ' + opts.length ); // number of selected options
return false; // don't return online form
};
</script>
how can i select multiple values without holding ctrl button
The following javascript function allows to select multiple items without using CTRL:
window.onmousedown = function (e) {
var el = e.target;
if (el.tagName.toLowerCase() == 'option' && el.parentNode.hasAttribute('multiple')) {
e.preventDefault();
var display = document.getElementById('display');
// toggle selection
if (el.hasAttribute('selected'))
{el.removeAttribute('selected');
var str = display.innerHTML;
str = str.replace(new RegExp(el.value+",?"), '');
display.innerHTML = str;
}
else {el.setAttribute('selected', ''); display.innerHTML += el.value + ', ';}
// hack to correct buggy behavior
var select = el.parentNode.cloneNode(true);
el.parentNode.parentNode.replaceChild(select, el.parentNode);
}
}
Source :source
I have modified to make it works with your code.
Result: jsfiddle
It's possible by overriding the normal behaviour of the mousedown event for your option-selector, setting it to just toggle the selected-state of the option like this:
$('option').mousedown(function(event) {
event.preventDefault();
$(this).prop('selected', !$(this).prop('selected')); // on => off => on
return false;
});

How to compare <option> “data-names” in an “if” statement?

I have a slight issue. I have options with a “value” and a “data-name”.
<option value=”A” data-name1=”X”>
<option value=”B” data-name1=”Y”>
I want the computer return a specific value if the selected option is a certain “data-name”
Say there are 2 “data-names”, X and Y.
How can I compare the data-name of the selected option to the 2 data-names, X and Y, to find out which one it is?
I’m thinking something along the lines of this:
var data_name1 = e.options[e.selectedIndex].dataset.name1;
if (data_name1 == “X”) {
…
}
else if (data_name == “Y”) {
…
}
else {
…
}
Is this possible?
Thanks!
Full code---
<script>
document.getElementById("selectElement").selectedIndex = -1; // so that no option //is selected when the page is loaded
function getData(){
var e = document.getElementById("qwert"); // get the <select> element
var data_name1 = e.options[e.selectedIndex].dataset.name1; // get the selected //<option> and its name1 data attribute
// var data_name2 = e.options[e.selectedIndex].dataset.name2; get the selected //<option> and its name2 data attribute
var value = e.options[e.selectedIndex].value; // get the value of the selected <option>
//Result
document.getElementById("data1").innerHTML = data_name1;
document.getElementById("value").innerHTML = value;
}
</script>
<select id="qwert" onclick="getData ()">
<option value="135" data-name1="M">A</option>
<option value="150" data-name1="R">B</option>
<option value="51" data-name1="R">C</option>
<option value="27" data-name1="M">D</option>
</select>
<p>
<label>data-name1 = </label>
<span>"</span><span id="data1"></span><span>"</span>
</p>
<p>
<label>value = </label>
<span>"</span><span id="value"></span><span>"</span>
</p>
You need to use the == operator to compare objects.
= is an assignment expression.
if (data_name1 == “X”) {
// Operations if data_name is equal to X
}
else if (data_name == “Y”) {
// Operations is data_name is equal to Y
}
else {
}

Displaying key and values of the options in a dropdown using javascript

function keyy(id)
{
var value;
var selected;
var select = document.getElementById(id);
if(value != null)
select.options[selected].text = value;
selected = select.selectedIndex;
var key;
key =select.options[selected].value;
value= select.options[selected].text;
select.options[selected].innerHTML = key;
}
<select id="Carss" name="Cars" onchange="keyy(this.id)" >
<option value="A">Audi</option>
<option value="M">Mercedes</option>
</select>
I have n dropdown values. When I select one value, the corresponding key should be displayed. The drop down should be the values and the display item shoud be the coresponding key.
Have atached the image for the reference.
My code :
var value;
var selected;
function keyy(id) {
var select = document.getElementById(id);
if(value != null)
select.options[selected].text = value;
selected = select.selectedIndex;
var key;
key =select.options[selected].value;
value= select.options[selected].text;
select.options[selected].text = key;
}
What you're trying to do is impossible (with a native <select>). The item you see in the closed <select> is simply the <option> that is currently selected. When you open the drop-down, you see the same <option> in two places - in the "selection" and in the "list". You cannot see a different value in each of the places, when it's the same <option>.
You could, however, show the selected value somewhere else, e.g. in a second element next to the <select>.
This is not a perfect answer..
But a possible work around..
function key() {
document.getElementById("Carss").style.width = "100px"
}
function key2() {
document.getElementById("Carss").style.width = "34px"
document.getElementById("Carss").blur();
}
<select id="Carss" name="Cars" onfocus="key()" onchange="key2()" style="width:34px">
<option value="A">Audi</option>
<option value="M">Mercedes</option>
</select>

Categories