Display previously selected options in select - javascript

Say I've got a HTML setup with some JS behind.
<select id="my-select" onchange="changeFunc()">
<option>A</option>
<option>B</option>
</select>
But I'm trying to make it so that the select HTML keeps track of which options have been clicked and displays those in the select's display rather than just the most recently clicked item. Some pseudo code might look like.
let selectedValues = [];
changeFunc() {
selectedValues.push(mySelect.value);
mySelect.DISPLAY = selectedValues.join(', ');
}
Is there any way to achieve this effect for a select element?

You can do this two ways either store the all previously select value in an array and display them in div as record OR create new option in the same select using and append them in an optgrp.
Solution: If you want display the previously selected option in the same select
Live Demo
let recSel = document.querySelector('#record_select')
function changeFunc(e) {
let opt = document.createElement('OPTION');
opt.textContent = e.options[e.selectedIndex].textContent
opt.value = e.options[e.selectedIndex].value
recSel.appendChild(opt);
}
<select id="my-select" onchange="changeFunc(this)">
<optgroup label="Current Select">
<option selected disabled>Choose</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="E">E</option>
<option value="F">F</option>
<option value="G">G</option>
</optgroup>
<optgroup label="Previous Selected" id="record_select">
</optgroup>
</select>
Solution: If you want display the previously selected records in a div with join(',')
Live Demo:
let selectedValues = [];
let recSel = document.querySelector('#record_select') //get el
//Store value
function changeFunc(e) {
selectedValues.push(e); //store selected value
recSel.textContent = selectedValues.join(', '); //display record of selected values
}
<select id="my-select" onchange="changeFunc(this.value)">
<option selected disabled>Choose</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="E">E</option>
<option value="F">F</option>
<option value="G">G</option>
</select>
<div id="record_select"></div>

Related

Swap a select text with javascript?

I have a example code here:
function swap() {
var sel1 = $("#se1 option:selected").text();
var sel2 = $("#se2 option:selected").text();;
console.log(sel1, sel2)
$("#se1").val(sel2);
$("#se2").val(sel1);
}
<select id="se1">
<option value="1">DOG</option>
<option value="2">CAT</option>
<option value="3">BIRD</option>
</select>
<button onclick="swap()">SWAP</button>
<select id="se2">
<option value="4">DOG</option>
<option value="5">CAT</option>
<option value="6">BIRD</option>
</select>
I want to swap se1 and se2 . Here is my code i tried:
function swap() {
var sel1 = $("#se1 option:selected").text();
var sel2 = $("#se2 option:selected").text();;
console.log(sel1, sel2)
$("#se1").val(sel2);
$("#se2").val(sel1);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<select id="se1">
<option value="1">DOG</option>
<option value="2">CAT</option>
<option value="3">BIRD</option>
</select>
<button onclick="swap()">SWAP</button>
<select id="se2">
<option value="4">DOG</option>
<option value="5">CAT</option>
<option value="6">BIRD</option>
</select>
It's work but it require Jquery 1.2.3 but i want to use Jquery 2.1.3. If i change script url to "https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js" but it isn't work
Thanks for help!
You shouldn't be swapping the values or the text of the two selected items in the lists. You just need to swap which item is selected in each list. Once that is done, that option will have whatever value the list has set up for it.
The version of JQuery you use here doesn't matter since what you are doing requires JQuery operations that have been in JQuery since the beginning.
var sel1 = $("#se1");
var sel2 = $("#se2");
function swap() {
let selection1 = sel1[0].selectedIndex; // Store the first list's selection
sel1[0].selectedIndex = sel2[0].selectedIndex;
sel2[0].selectedIndex = selection1;
// Test
console.log(sel1.val(), sel2.val());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<select id="se1">
<option value="1">DOG</option>
<option value="2">CAT</option>
<option value="3">BIRD</option>
</select>
<button onclick="swap()">SWAP</button>
<select id="se2">
<option value="4">DOG</option>
<option value="5">CAT</option>
<option value="6">BIRD</option>
</select>

How to force a select to keep always the same selected value

Let's say we have multiple forms, each form has 40 selects, the ids of each select have the following structure:
#id_form-X-{field_name}
Let's say for example, of those 40 selects, we want 3 of them to be unmodifiable for each form when we change the value of the select, so it will always show the same selected value.
The 3 selects we want to change have the following field_name: ps2_0, ps2_1 and ps2_3.
So I'm looking for a generic solution that works for:
id_form-0-ps2_0
id_form-0-ps2_1
id_form-0-ps2_3
id_form-1-ps2_0
id_form-1-ps2_1
id_form-1-ps2_3
id_form-N-ps2_0
id_form-N-ps2_1
id_form-N-ps2_3
...
...
...
Dummy example:
<select name="cars" id="cars">
<option selected value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
If, for example, the user clicks on the select and selects, for example Saab, the select will show again the value selected by default: Volvo.
I cannot use the 'readonly' or 'disabled' properties for the selects.
What I've tried so far:
$(document).ready(function() {
var previous = "initial prev value";
$("select").on('click', function () {
previous = $(this).val();
}).change(function() {
$(this).val() = previous;
});
});
I'm trying to 'force' the changed select to keep the previous value but didn't work.
Simple Solution
Reset the value of select with initial value on change.
const selectDD = document.getElementById('cars');
const selectedNode = selectDD.value;
selectDD.onchange = (e) => {
selectDD.value = selectedNode;
}
<select name="cars" id="cars">
<option selected value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
Much Generic Solution
There should be some unique identifier to differentiate between nodes that can be changed and those to be kept unchanged. Here I have added an unchanged custom attribute to select. Pick thode nodes with that custom attribute and on change of that select, reset its value to initial value.
Example
const selectDD = document.querySelectorAll('[unchanged]');
selectDD.forEach((node) => {
node.attributes.initialValue = node.value;
node.onchange = (e) => {
e.target.value = node.attributes.initialValue;
}
})
You cant change this
<select name="cars" id="cars" unchanged>
<option selected value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br/>
You cant change this
<select name="gender" id="gender" unchanged>
<option selected value="male">Male</option>
<option value="female">female</option>
</select>
<br/>
You can change this
<select name="age" id="age">
<option selected value="10">10</option>
<option value="15">15</option>
</select>
If you use querySelectorAll to generate a nodelist of all the select menus you could assign a default attribute( using dataset here for instance) and set the value within an event listener so that this default attribute is always selected
document.querySelectorAll('form select').forEach( sel => {
sel.dataset.def=sel.options[sel.selectedIndex].value;
sel.addEventListener('change',function(e){
this.value=this.dataset.def
})
})
<form>
<select name='cars'>
<option selected value='volvo'>Volvo
<option value='saab'>Saab
<option value='mercedes'>Mercedes
<option value='audi'>Audi
</select>
<select name='fruit'>
<option selected value='apple'>Apple
<option value='banana'>Banana
<option value='mango'>Mango
<option value='plum'>Plum
</select>
</form>
Maintain an object which specifies the restricted Select items and the indexes they should always defaults to
let allowedIndexes = {
cars: 0,
bikes: 1
}
function preventChange(e) {
if (Object.keys(allowedIndexes).includes(e.currentTarget.id)) {
let fixedIndex = allowedIndexes[e.currentTarget.id];
e.currentTarget.selectedIndex = fixedIndex;
}
}
<select name="cars" id="cars" onChange="preventChange(event)">
<option selected value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select name="bikes" id="bikes" onChange="preventChange(event)">
<option value="honda">honda</option>
<option selected value="kavasaki">kavasaki</option>
<option value="suzuki">suzuki</option>
<option value="yamaha">yamaha</option>
</select>
It's somewhat uncomfortable when one's answer is copied.

JavaScript: select1 on-change to populate specific options (with 2 values) in select2

Using the following code:
$("#select1").change(function() {
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#select2').html(options);
});
work fine and populate the specific options, but how to do it if I have:
one values for every option in select1:
<option value="1">some text</option>
and two values for every option in select2:
<option value="1,1">some other text</option>
UPDATE for more clarification:
The first select is like this:
<select id="select1">
<option value="1">text 1</option>
<option value="2">text 2</option>
<option value="3">text 3</option>
<option value="4">text 4</option>
<option value="5">text 5</option>
<option value="6">text 6</option>
<option value="7">text 7</option>
...
</select>
and the second one:
<select id="select2">
<option value="3">some text ...</option>
<option value="3">some text ...</option>
<option value="5">some text ...</option>
<option value="1">some text ...</option>
<option value="4">some text ...</option>
<option value="7">some text ...</option>
<option value="2">some text ...</option>
<option value="2">some text ...</option>
<option value="6">some text ...</option>
<option value="6">some text ...</option>
...
</select>
If I select the 2nd option from select1, the select2 will be like this
<select id="select2">
<option value="2">some text ...</option>
<option value="2">some text ...</option>
</select>
But, I'm looking for the same functionality when select2 option value is like (i.e):
<option value="2,24">some text ...</option>
If I understood what you need, you use value for filtering, and when you submit the form you need another data to send
I think the most appropriate way to achieve what you need to put the options of the second select in an array
then filter the array when first select option item selected
then build the second select options
var select2options = [
{ filterValue="1", text="some text", itemValue="2"},
{....},
...
]
then when you select an item from select1
`
$("#select1").change(function() {
var id = $(this).val();
var options = select2Options.filter( item => item.filterValue == id);
var select2HtmlOptions = '';
for(let i=0;i<options.length;i++){
select2HtmlOptions+= <option value="itemValue" data-
filter="filterValue">text</option>';
}
$('#select2').html(select2HtmlOptions);
});
`
and when you submit you can get
var filter = $( "#select2:selected" ).data('filter');
var text = $( "#select2:selected" ).text();
var optionValue = $( "#select2:selected" ).val()
try below
$("#select1").change(function() {
var id = $(this).val();
$("#select2 option").each(function() {
if ($(this).val() == id) {
$(this).show();
} else {
var arrVal = $(this).val().split(',');
if(arrVal.indexOf(id)>-1)
$(this).show();
else
$(this).hide();
}
});
});
https://jsfiddle.net/s41rjkhL/5/

How to get the values and text of all the options of select element

I have a select element with a huge list of options (more than 2000).
I'd like to get the values and name of each option, one by line.
<select name='county_city' id='county_city'>
<OPTION value="51421">City one</OPTION>
<OPTION value="51422">City two</OPTION>
<OPTION value="51423">City three</OPTION>
<OPTION value="51424">City four</OPTION>
</select>
What I'd like is,
51421 = City one
51422 = City two
51423 = City three
51424 = City four
One option per line..
Thanks.
First, you need to iterate through the options array, and collect the values & text into a data array, then you can do whatever you feel like with it, for instance print it to the page like so:
var data = [];
$('#county_city option').each(function(){
var current = $(this);
data.push({
value: current.val(),
text: current.html()
})
});
$.each(data, function(){
console.log(this);
$('#result').append(this.value + ': ' + this.text)
.append('<br />');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name='county_city' id='county_city'>
<OPTION value="51421">City one</OPTION>
<OPTION value="51422">City two</OPTION>
<OPTION value="51423">City three</OPTION>
<OPTION value="51424">City four</OPTION>
</select>
<div id="result"></div>
use the following code :-
HTML
<select name='county_city' id='county_city'>
<OPTION value="51421">City one</OPTION>
<OPTION value="51422">City two</OPTION>
<OPTION value="51423">City three</OPTION>
<OPTION value="51424">City four</OPTION>
</select>
JQuery
$(document).ready(function() {
$("#county_city OPTION").each(function(index){
alert(this.value);
alert(this.text);
});
});

Two HTML selects with differing selected values

I got following HTML code:
<select id="first">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="second">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
So both of them have same data. I need to secure, that user can't select same value in both of them.
I hoped, that JQuery has some nice feature like:
$("#first").getOptions()
or even
$("#first").setOptions()
but unfortunately, it doesn't. This makes it very complicated for me, because I don't know JQuery very well ...
So, what is the best approach to solve my problem?
You can get the value of the currently selected option by doing:
$('#first option:selected').text();
$('#second option:selected').text();
Assuming I understand your question, you don't want the user to be able to enter the same value in each box. So, something similar to:
$first = $('#first');
$second = $('#second');
$first.on('change', function() {
$second.find('option').attr('disabled', false);
var firstVal = $first.find('option:selected').text();
$second.find('option:contains("'+ firstVal +'")').attr('disabled', true);
});
$second.on('change', function() {
$first.find('option').attr('disabled', false);
var secondVal = $second.find('option:selected').text();
$first.find('option:contains("'+ secondVal +'")').attr('disabled', true);
});
I should probably note that there are ways for you to achieve your getOptions() and setOptions() ideas, you can do $select.find('option') to get the options. For setting them, define some options in html and set the select element's innerHTML to those elements:
var options = '<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>';
$select.html(options);
JSFiddle demo
You can disable single options in your select
<select id="second">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2" disabled>Two</option>
<option value="3">Three</option>
</select>
Handle event onSelect on first select and based on it disable proper <option> in second select
When one is changed, if the other is the same, you could change it back to default, like this.
$(document).on('change', '#first', function() {
var firstVal = $('#first').val();
var secondVal = $('#second').val();
if (firstVal == secondVal) {
$('#second').val(0);
}
});
$(document).on('change', '#second', function() {
var firstVal = $('#first').val();
var secondVal = $('#second').val();
if (firstVal == secondVal) {
$('#first').val(0);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="first">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="second">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
Try this(codepen):
HTML:
<select id="first">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="second">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
Javascript/jQuery:
var strUser;
var strUser2;
$(function() {
$("#first").change(function() {
var e = document.getElementById("first");
strUser = e.options[e.selectedIndex].text;
if (strUser == strUser2) {
alert("Dropdowns contain the same value. Change one.")
document.getElementById("first").disabled=true;
} else {
document.getElementById("second").disabled=false;
}
});
});
$(function() {
$("#second").change(function() {
var e = document.getElementById("second");
strUser2 = e.options[e.selectedIndex].text;
if (strUser2 == strUser) {
alert("Dropdowns contain the same value. Change one.")
document.getElementById("second").disabled=true;
} else {
document.getElementById("first").disabled=false;
}
});
});
Essentially, this code will retrieve selected values from the dropdowns on change, and then a comparison will be made. If the values are equal, the recently selected dropdown will be disabled. You then will have to select a different value in the other dropdown to re-enable the disabled dropdown. Here's the codepen that displays the working functionality. This will not allow a user to select two of the same values without a dropdown being disable and turned off.

Categories

Resources