get unselected option from multiple select list - javascript

I have a multiple select list. When user unselects the selected option, I want to know the value of the unselected option made by user. How do I capture it?
My sample code is as below.
<select multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
I have following jquery code to allow user to select multiple options
$('option').mousedown(function(){
e.preventDefault();
$(this).prop('selected', $(this).prop('selected') ? false :true);
});

Mouse events aren't available cross browser
My suggestion would be always store array of previous values on the select.
On every change you can then compare to prior value array and once found update the stored array
$('#myselect').on('change', function() {
var $sel = $(this),
val = $(this).val(),
$opts = $sel.children(),
prevUnselected = $sel.data('unselected');
// create array of currently unselected
var currUnselected = $opts.not(':selected').map(function() {
return this.value
}).get();
// see if previous data stored
if (prevUnselected) {
// create array of removed values
var unselected = currUnselected.reduce(function(a, curr) {
if ($.inArray(curr, prevUnselected) == -1) {
a.push(curr)
}
return a
}, []);
// "unselected" is an array
if(unselected.length){
alert('Unselected is ' + unselected.join(', '));
}
}
$sel.data('unselected', currUnselected)
}).change();
DEMO

Great question, i wrote some codes for detecting unselected options using data attributes.
$('#select').on('change', function() {
var selected = $(this).find('option:selected');
var unselected = $(this).find('option:not(:selected)');
selected.attr('data-selected', '1');
$.each(unselected, function(index, value){
if($(this).attr('data-selected') == '1'){
//this option was selected before
alert("I was selected before " + $(this).val());
$(this).attr('data-selected', '0');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple id="select">
<option data-selected=0 value="volvo">Volvo</option>
<option data-selected=0 value="saab">Saab</option>
<option data-selected=0 value="opel">Opel</option>
<option data-selected=0 value="audi">Audi</option>
</select>

If I understand you correctly, you want the option that just got unselected, right?
if so, try this:
create a variable "lastSelectedValue" (or whatever you want to call it). When you select an option, assign to it, when you change the selected option, you can get the value and use it, and assign to it again
var lastSelectedOption = '';
$('select').on('change', function(){
//do what you need to do
lastSelectedOption = this.val();
});
here's a fiddle: https://jsfiddle.net/ahmadabdul3/xja61kyx/
updated with multiple: https://jsfiddle.net/ahmadabdul3/xja61kyx/
not sure if this is exactly what you need. please provide feedback

As mentioned by others, the key would be to compare the previous selected values with current value. Since you need to figure out the removed value, you can check if the lastSelected.length > currentSelected.length and then simply replace the currentSelected from the lastSelected to get the results.
var lastSelected = "";
$('select').on('change', function() {
var currentSelected = $(this).val();
if (lastSelected.length > currentSelected.length) {
var a = lastSelected.toString().replace(currentSelected.toString(),"");
alert("Removed value : " + a.replace(",",""));
}
lastSelected = currentSelected;
});
Working example : https://jsfiddle.net/DinoMyte/cw96h622/3/

You can try make it
$('#link_to_id').find('option').not(':selected').each(function(k,v){
console.log(k,v.text, v.value);
});
With v.text get the Text
With v.value get the Value

Related

There is a way to get all the option values in the SELECT TAG without an ID?

do you know if there is a way to take all the values in the OPTION VALUE included in a SELECT?
i Will show you an example, I have this code:
<SELECT onChange="chData(this,this.value)">
<OPTION VALUE=MIPS1 >MIPS
<OPTION VALUE=MSU1 >MSU
<OPTION VALUE=PERCEN1 >% CEC
<OPTION VALUE=NUMGCP1 >nCPU
</SELECT>
I only know the first value which is MIPS1, and I need to take the other values. The is a way to write that if I know the first MIPS1 I will search for the other values Included from the ?
Thanks in advance :)
You can get the <select> element that has an option with a specific value using something like this:
const select = document.querySelector('option[value=MIPS1]').closest('select');
Once you have the <select> element you can retrieve it's options using something like this:
const options = select.querySelectorAll('option');
Or:
const options = select.options;
As #charlietfl mentioned, .closest is not supported by all browsers, instead of that, you could use .parentElement.
jQuery version
var opt = "MIPS1";
const $sel = $("option[value='"+opt+"']").parent()
const options = $("option",$sel).map(function() { return this.value }).get()
console.log(options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<SELECT onChange="chData(this,this.value)">
<OPTION VALUE=MIPS1>MIPS
<OPTION VALUE=MSU1>MSU
<OPTION VALUE=PERCEN1>% CEC
<OPTION VALUE=NUMGCP1>nCPU
</SELECT>
The example below shows how you can do this. The Jquery is fully commented.
Let me know if it isn't what you were hoping for.
Demo
// Create array
var options = [];
// Load option value you're looking for into a variable
var search_term = "MIPS1";
// Find option with known value, travel up DOM tree to select and then find all options within it
$("option[value='" + search_term + "']").closest("select").find("option").each(function() {
// Add values to array
options.push($(this).val());
});
// Print the array
console.log(options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<SELECT onChange="chData(this,this.value)">
<OPTION VALUE=MIPS1>MIPS
<OPTION VALUE=MSU1>MSU
<OPTION VALUE=PERCEN1>% CEC
<OPTION VALUE=NUMGCP1>nCPU
</SELECT>
I think it is a bad idea not to give id to your html element in the first place, however if you need to do it that way, then the code below assumes you have only one select tag on your page.
let select = document.querySelector('select');
options = select.childNodes.filter((c) => c.tagName==='OPTION')
.map((o) => o.value);
console.log(options)
This will help you get: selected value, selected text and all the values in the dropdown.
$(document).ready(function(){
$("button").click(function(){
var option = $('option[value="MIPS1"]');
var select = option.parent();
var value = $(select).find(":selected").val();
var optionName = $(select).find(":selected").text();
var result = "value = "+value+"\noption name = "+optionName+"\nall values = ";
$(select).each(function(){
result+=($(this).text()+" ");
});
console.log(result);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
<option value=MIPS1 >MIPS</option>
<option value=MSU1 >MSU</option>
<option value=PERCEN1 >% CEC</option>
<option value=NUMGCP1 >nCPU</option>
</select>
<button>click</button>

JQuery get the value of the newly selected/unselected element of a select [duplicate]

I have a HTML select list, which can have multiple selects:
<select id="mySelect" name="myList" multiple="multiple" size="3">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option> `
<option value="4">Fourth</option>
...
</select>
I want to get an option's text everytime i choose it. I use jQuery to do this:
$('#mySelect').change(function() {
alert($('#mySelect option:selected').text());
});
Looks simple enough, however if select list has already some selected options - it will return their text too. As example, if i had already selected the "Second" option, after choosing "Fourth" one, alert would bring me this - "SecondFourth". So is there any short, simple way with jQuery to get only the "current" selected option's text or do i have to play with strings and filter new text?
You could do something like this, keeping the old value array and checking which new one isn't in there, like this:
var val;
$('#mySelect').change(function() {
var newVal = $(this).val();
for(var i=0; i<newVal.length; i++) {
if($.inArray(newVal[i], val) == -1)
alert($(this).find('option[value="' + newVal[i] + '"]').text());
}
val = newVal;
}); ​
Give it a try here, When you call .val() on a <select multiple> it returns an array of the values of its selected <option> elements. We're simply storing that, and when the selection changes, looping through the new values, if the new value was in the old value array ($.inArray(val, arr) == -1 if not found) then that's the new value. After that we're just using an attribute-equals selector to grab the element and get its .text().
If the value="" may contains quotes or other special characters that would interfere with the selector, use .filter() instead, like this:
$(this).children().filter(function() {
return this.value == newVal[i];
}).text());
Set a onClick on the option instead of the select:
$('#mySelect option').click(function() {
if ($(this).attr('selected')) {
alert($(this).val());
}
});
var val = ''
$('#mySelect').change(function() {
newVal = $('#mySelect option:selected').text();
val += newVal;
alert(val); # you need this.
val = newVal;
});
or let's play some more
val = '';
$('#id_timezone')
.focus(
function(){
val = $('#id_timezone option:selected').text();
})
.change(
function(){
alert(val+$('#id_timezone option:selected').text())
});
Cheers.

Jquery select variable by id

I am trying to get the content of a select option which is specified by the selected options.
I can get the selected options to tell me the data-parent but I can't use that to get the text of the parent option.
<select id="addCatSelectCats" multiple="multiple">
<option id="Cat55" data-parent="5">Parent Cat</option>
<option id="Cat357" data-parent="55">Sub Cat</option>
</select>
$(document).on('change', '#addCatSelectCats',function() {
$("#addCatSelectCats option").each(function(){
if($(this).is(':selected')){
var dataparent = $(this).attr('data-parent');
if(dataparent > 0){
var parent = $('#Cat'+dataparent).text();
alert(parent);
}
}
});
});
Where am I going wrong?
You could do with a little less code
$(document).on('change', '#addCatSelectCats',function() {
var parent = $("#addCatSelectCats option:selected").text();
alert(parent);
});

Javascript/jQuery: ensuring unique option added to pulldown

I have an HTML pulldown menu along with a text element that allows users to add new options to the menu. I'd like to make sure that every option that is added is unique. The following two lines were the first option I thought of that worked (option value = innHTML for all of the options). I'm wondering if there's a more elegant solution to this -- the second line just seems clunky. It also doesn't handle spaces in the new_name string.
var new_name = document.getElementById("preset_name").value
var unique_name = $("option[value="+new_name+"]").length === 0 ? true : false
Do you need something like this?
HTML:
<select id="myselect">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<input id="newoption" type="text" />
<button id="check">Check</button>
jQuery:
$(document).ready(function() {
$("button#check").click(function() {
var newOpt = $("input#newoption").val();
$("#myselect option").each(function(){
var text = $(this).val();
if(newOpt.length>0 && text.indexOf(newOpt)!=-1){
console.log("already present!");
}
});
});
});
jsfiddle
Combining the two comments on the question, you could streamline down to 1 line:
var unique_name = $("option[value="+$("#preset_name").val()+"]").length === 0;
You don't need the ternary, as the === results in a true or false value. Unless you need the test value again, you don't even need to store it in a variable - you can just retrieve it with jQuery.

How to get the value of a multiple option dropdown?

Say I have this dropdown:
<select name="color" multiple="multiple">
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</select>
So basically more than 1 color can be selected. What I'd like is that if a user selects red, and then clicks green, i'd like a function to be called each time which pops up a message box saying the color which was most recently clicked.
I've tried this:
<option value="red" onclick="alert('red');">Red</option>
<option value="green" onclick="alert('green');">Green</option>
<option value="blue" onclick="alert('blue');">Blue</option>
This works in firefox and chrome, but not in IE.
Any ideas?
$("select[name='color']").change(function() {
// multipleValues will be an array
var multipleValues = $(this).val() || [];
// Alert the list of values
alert(multipleValues[multipleValues.length - 1]);
});
Here's another examples: http://api.jquery.com/val/
The following code should do what I think you're after. Each time an item is selected, it compares the current list of selections against the previous list, and works out which items have changed:
<html>
<head>
<script type="text/javascript">
function getselected(selectobject) {
var results = {};
for (var i=0; i<selectobject.options.length; i++) {
var option = selectobject.options[i];
var value = option.value;
results[value] = option.selected;
}
return results;
}
var currentselect = {};
function change () {
var selectobject = document.getElementById("colorchooser");
var newselect = getselected(selectobject);
for (var k in newselect) {
if (currentselect[k] != newselect[k]) {
if (newselect[k]) {
alert("Option " + k + " selected");
} else {
alert("Option " + k + " deselected");
}
}
}
currentselect = newselect;
}
</script>
</head>
<body>
<select id="colorchooser"
name="color"
multiple="multiple"
onchange='javascript:change();'
>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</select>
</body>
</html>
It should work just as well in Internet Explorer as Firefox et al.
Since you using jQuery,I suggest you to take a look at this superb plugins. This plugins will transform a multiple select dropdown into a checkbox list, so user can select multiple values with easy.
To get the values, I suggest you use fieldValue methods from jQuery form plugins. It's a robust way to get value from any type of form element. Beside, you can use this plugins to submit your form via AJAX easily.
This will alert only the last (most recent) selected value. Calling $(this).val() using the select's change handler will return an array of all your selected values:
$(document).ready(function() {
$("select[name=color] option").click(function() {
alert($(this).val());
});
});
I am not sure what you exactly want. This will always alert the last selected color:
$(function(){
var selected = Array();
$('select[name=color] option').click(function() {
if($(this).is(':selected')) {
selected.push($(this).val());
}
else {
for(var i = 0; i < selected.length;i++) {
if(selected[i] == $(this).val()) {
selected = selected.splice(i,1);
}
}
}
alert(selected[selected.length -1])
});
});
The array is used to maintain the history of selected colors.
For the last clicked color, it is simpler:
$(function(){
$('select[name=color] option').click(function() {
alert($(this).val());
});
});
This is so complicated to accomplish that I used a simpler option of listing the items with a checkbox next to them and a select/unselect all button. That works much better and is also supported by IE. Thanks to everyone for their answers.

Categories