How to get the value of a multiple option dropdown? - javascript

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.

Related

how can i select item from option menu if i have one item

I want to select an item from option select menu when I have just one item in order to use in my next function ( $('#').on("change", function() {}) )
it's work when I have more than one item in the menu but if there is one item when I clicking on that one item there is no any result:
from the backend item one=[1] two=[1,2] and three=[1,2,3], it is ok for selecting two and three but not for item one which I have only one number inside
HTML
<select id = "fir">
<option>one</option>
<option>two</option>
<option>three</option>
</select>
<select id="sec" >
<option ></option>
</select>
<input id="tbl_S2" type="text" >
JavaScript
$('#fir').on("click", function() {
var schem =$("#fir").val();
$.ajax({
type: 'GET',
url:'url/'+schem,
success:function(data2){
$("#sec").empty();
for (var i = 0; i < data2.length; i++) {
$("#sec").append("<option>"+data2[i]+"</option>");
}
}
}
},
});
});
$('#fir').on("change", function() {
$('#sec').on("change", function() {
$('#tbl_S2').html( "hello");
});
});
In order for a particular item to be selected, you should use the option selected method, i.e. append selected after data2[i] if there is only one item in the list. (add an if statement)
Your if statement would look similar to this:
if (data2.length == 1){
$("#sec").append("<option selected>"+data2[i]+"</option>");
}
else{
for (var i = 0; i < data2.length; i++) {
$("#sec").append("<option>"+data2[i]+"</option>");
}
}
The HTML output would look something like this
<select>
<option value="data" selected>Your variable</option>
</select>
Hope this helps
EDIT:
The below snippet is a simple example of how to show both values from two dropdowns, even when one only has one item in the dropdown. Please note that in the example, if the second dropdown is changed (if you un-comment back in the second option), the output text doesn't change until the other dropdown is clicked. I'm sure I could have corrected this with a little more time spent. There is a jsbin here
I am aware that your list is not static, but dynamic, that you are using ajax to populate, however I hope this provides a starting point.
var secSelect= "";
function showSelect(str) {
var schem1="";
var returnText="";
var schem1= str;
var sec1=document.getElementById("sec");
var hello=document.getElementById("text1");
var sec2=sec1.value;
if (secSelect !=""){
sec1=secSelect;
}
hello.innerHTML = " hello";
returnText= schem1 +" " +sec2 + hello.value;
document.getElementById("text1").innerHTML = returnText;
};
function passSelect(str2){
secSelect=str2;
}
#text1{background-color:white!important;
width:150px;
display:inline-block;
height:13.5px;
vertical-align:top;}
#sec, #fir{display:inline-block;
vertical-align:top;
}
<select id="fir" onclick="showSelect(this.value);">
<option>one</option>
<option>two</option>
<option>three</option>
</select>
<select id="sec" onclick="passSelect(this.value);">
<option>one</option>
<!--<option>rach</option>-->
</select>
<textarea id="text1" type="text"></textarea>

get unselected option from multiple select list

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

Javascript / JQuery - Sorting by Multiple Classes

having a bit of trouble here, any help would be greatly appreciated...
I am trying to hide and show a bunch of list items based on several classes assigned to them.
In my JS Fiddle Example I have several items with classes relating to their description.
I have managed to hide and show these, but complex selections are not possible...
example: If I wanted to only see fabrics that are "premium", "blue" and "linen".
Something like this (that works lol) is what I am after...
$('.sel_range').click(function() {
range = document.getElementById("range").value;
if ($('.fabric_option').hasClass(range)) {
$('.' + range).fadeIn('fast', function() {
!$('.fabric_option').hasClass(range).fadeOut("fast");
});
}
});
Something like this should work
var selects = $('#range, #fabric, #colour');
selects.on('change', function() {
var el = selects.map(function(i, item) {
return item.value.indexOf('all_') === 0 ? '' : '.' + item.value;
}).get().filter(function(x) {
return x.length;
}).join('');
$('#fabric_options li').show().not(s?s:'*').hide();
});
FIDDLE
It starts with showing all the list items, then joins the values together to create a clas selector, leaving out the class if all_something is selected etc. and then hides everything that doesn't match, and if nothing is selected excludes everything.
I think it can be solved like this:
var range, fabric, colour;
var updateShown = function() {
$('li').show()
if (range) {
$('li:not(.' + range + ')').hide();
}
if (fabric) {
$('li:not(.' + fabric + ')').hide();
}
if (colour) {
$('li:not(.' + colour + ')').hide();
}
}
// Range
$('#range').change(function() {
range = $(this).val();
updateShown();
});
// Fabric
$('#fabric').change(function() {
fabric = $(this).val();
updateShown();
});
// Colour
$('#colour').change(function() {
colour = $(this).val();
updateShown();
});
With value="" of each select first option
<select id="range">
<option class="sel_range" value="">All Ranges</option>
<option class="sel_range" value="luxury">Luxury</option>
<option class="sel_range" value="premium">Premium</option>
<option class="sel_range" value="base">Base</option>
</select>
<select id="fabric">
<option class="sel_fabric" value="">All Fabrics</option>
<option class="sel_fabric" value="leather">Leather</option>
<option class="sel_fabric" value="linen">Linen</option>
<option class="sel_fabric" value="cotton">Cotton</option>
</select>
<select id="colour">
<option class="sel_colour" value="">All Colours</option>
<option class="sel_colour" value="red">Red</option>
<option class="sel_colour" value="blue">Blue</option>
<option class="sel_colour" value="green">Green</option>
</select>
jsFiddle demo
what about this?
$('#range').on('change',function () {
range = $("#range").val();
$('li').each(function(){
if(!$(this).hasClass(range)){
$(this).hide();
}else{
$(this).show();
}
});
});
// just for range, rest in fiddle
http://jsfiddle.net/J3EZX/6/
If you're using jQuery, just string them together with a . and no space, e.g.:
$(".linen.red.base").text("Help! I'm being replaced!");

Change Select tag value using JavaScript

I'm trying to change a value from a select tag using JavaScript. Let's say that I have this textbox, and if that textbox is null, no changes will be done and the value of the select tag options will be as is. But if that textbox is filled, then I have to assign a different value aside from the ones in the select tag options.
Here's what I'm trying to do:
HTML:
<input type="text" id="txtTest" />
<select name="rdoSelect" id="rdoSelect">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
JavaScript:
if (document.getElementById('txtTest').value===null)
{
document.getElementById('rdoSelect').value;
}
else
{
document.getElementById('rdoSelect').value = "option 3";
}
I can't make it work. I've tried pointing it to an element/variable rather than to a value and it still doesn't work:
var test = document.getElementById('rdoSelect');
test.value = "option 3";
I need help, please. Thanks!
Try using SelectIndex method. Please refer the below code.
I added OnChange event to input text to test this sample.
<html>
<head>
<script language="javascript">
function test()
{
if (document.getElementById('txtTest').value=='')
{
document.getElementById("rdoSelect").selectedIndex = 0;
}
else
{
document.getElementById("rdoSelect").selectedIndex = 1;
}
}
</script>
</head>
<body>
<input type="text" id="txtTest" onchange="test();" />
<select name="rdoSelect" id="rdoSelect">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
</body>
</html>
HTMLSelectElement doesn't let you set the value directly. It's possible to have many or zero <option>s with a particular value, so it's not a straightforward 1:1 mapping.
To select an option you can either set its selected property to true, or set the selectedIndex property of the select to the option number.
There is no option 3 in your select—are you trying to add a new option?
eg
function setOrCreateSelectValue(select, value) {
for (var i= select.options.length; i-->0;) {
if (select.options[i].value==value) {
select.selectedIndex= i;
return;
}
}
select.options[select.options.length]= new Option(value, value, true, true);
}
Is this happening on button click or onkeyup? Either way in the function you can add value to dropdownlist using this:
dropdownlist.append(
$("<option selected='selected'></option>").val(sValId).html(sVal)
);
Or you colud try this
var optn = document.createElement("OPTION");
optn.text = "--Select--";
optn.value = "0";
baseCurve.options.add(optn);`
if (document.getElementById('txtTest').value===null)
{
document.getElementById('rdoSelect').value;
}
else
{
var val = document.getElementById('txtTest').value
for(var i, j = 0; i = rdoSelect.options[j]; j++) {
if(i.value == val) {
rdoSelect.selectedIndex = j;
break;
}
}
}
Take a look at this jsfiddle, it's using jquery, which
is probably the most common solution. Hope it helps.
http://jsfiddle.net/GkLsZ/
$(function() {
$('#btnChange').on('click', function() {
var value = $.trim($('#txtTest').val());
if (!!value) {
$('#rdoSelect')
.append($("<option></option>")
.attr("value", value)
.attr("selected", "selected")
.text(value));
}
});
});

Loop over Dropdownlist

I want to loop over a Dropdownlist and write the value of the selected Item in a label.
I've done it before with a selection of Radio buttons but with the dropdownlist it won't work.
Now, some Code.
Here is the generated HTML Code Values are not interesting.
<select id="alternativeNumbers" name="alternativeNumbers">
<option value="1_A">Text</option>
<option value="2_B">Text</option>
<option value="3_C">Text</option>
<option value="4_D">Text</option>
<option value="5_E">Text</option>
<option value="6_F">Text</option>
</select>
The Code to bind the event to the Dropdownlist.
$(function () {
var dropdown = document.getElementsByName("alternativeNumbers");
$(dropdown ).change(function () {
updateAlternativeDropdown();
});
});
And finally the method which is called by the event. This should fill the labels.
function updateAlternativeDropdown() {
var dropdown = document.getElementsByName("alternativeNumbers");
var lengthDropDown = addAlternativeArticleNumberDropdown.length;
for (var i=0; i < lengthDropDown; i++)
{
//This alert is for the behavior of the output!
alert(addAlternativeArticleNumberDropdown[i].value);
if (addAlternativeArticleNumberDropdown[i].selected) {
var valueOfDropdown = addAlternativeArticleNumberDropdown[i].value;
var splittedValues = valueOfDropdown.split("_");
document.getElementById("label1").innerText = splittedValues[0];
document.getElementById("label2").innerText = splittedValues[1];
}
}
};
I hope this is enough information, now the Problem / Current behavior:
The method updateAlternativeDropdown() is called fine but then the alert inside the loop returns the value of first element, value of the selected element and this 3 times. (I guess because of the 6 elements in this element)
Furthermore because of this my if-statement isn't entered. Currently I#m kind of clueless where this problem comes from.
Thanks in advance.
You don't have to iterate dropdown's options. You can access selected option like this:
dropdown.options[dropdown.selectedIndex].value
Update your updateAlternativeDropdown function:
function updateAlternativeDropdown() {
var dropdown = document.getElementById("alternativeNumbers"),
splittedValues = dropdown.options[dropdown.selectedIndex].value.split('_');
document.getElementById("label1").innerHTML = splittedValues[0];
document.getElementById("label2").innerHTML = splittedValues[1];
}
$('#alternativeNumbers').change(updateAlternativeDropdown);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
label1: <span id="label1">-</span><br />
label2: <span id="label2">-</span><br />
<select id="alternativeNumbers" name="alternativeNumbers">
<option value="1_A">Text</option>
<option value="2_B">Text</option>
<option value="3_C">Text</option>
<option value="4_D">Text</option>
<option value="5_E">Text</option>
<option value="6_F">Text</option>
</select>
working Example

Categories