How to select multiple value from a listbox - javascript

I have a below code where if I select one value, it works fine, but now I need such that when I select multiple values from the listbox, i have to get the value of selected values. How do i go about it?
Here is the code,
HTML Code:
<select id="attributeNames" name="attributeNames" size="5" multiple="multiple"
onchange="getUniqueValues(value)">
<option value="Apple"> Apple </option>
<option value="Mango"> Mango </option>
<option value="Orange"> Orange </option>
<option value="Banana"> Banana </option>
</select>
JavaScript:
function getUniqueValues(value){
alert(value);
}
For instance:
If I select Apple, then I get alert saying apple, now if I select apple & mango, I have to get the alert having apple & mango values. Facing problem here.
Here is the code: http://jsfiddle.net/5VtE3/2/
Thanks in advance,

Here is an example on how to do it -
HTML -
<select id="attributeNames" name="attributeNames" size="5" multiple="multiple">
<option value="Apple"> Apple </option>
<option value="Mango"> Mango </option>
<option value="Orange"> Orange </option>
<option value="Banana"> Banana </option>
</select>
​
JS -
window.onload = function () {
var listbox = document.getElementById('attributeNames');
listbox.onchange = function () {
for(var index = 0; index < this.children.length; index++) {
if (this.children[index].selected) {
console.log(this.children[index].value);
}
}
}​;
};
Live Demo.

If you dont mind using jquery, -
function getUniqueValues(){
var k=0;
var selected_list = {};
$('#attributeNames option').is(':selected').each(function(){
selected_list[k++] = $(this).val();
});
alert(selected_list);
}
OR
function getrUniqueValues(){
$('#attributeNames option').is(':selected').each(function(){
alert($(this).val());
});
}

You might want to try checkboxes
<input type="checkbox" name="fruit" value="apple">Apple<br/>
<input type="checkbox" name="fruit" value="banana">Banana
Or you should just try to make:
<select id="attributeNames" name="attributeNames" size="5" multiple="multiple" onChange="getUniqueValues()" >
<option value="Apple"> Apple </option>
<option value="Mango"> Mango </option>
<option value="Orange"> Orange </option>
</select>
function getUniqueValues(){
var values = this;
}

Try this:
<select id="attributeNames" onchange="getUniqueValues.call(this)" name="attributeNames" size="5" multiple="multiple">
<option value="Apple"> Apple </option>
<option value="Mango"> Mango </option>
<option value="Orange"> Orange </option>
<option value="Banana"> Banana </option>
</select>
function getUniqueValues(){
for(var i = 0; i < this.options.length; i++){
if(this.options[i].selected)
alert(this.options[i].value);
}
}
jsfiddle: http://jsfiddle.net/5VtE3/7/

function getValue(id) {
var retval = "";
var lstdatabase = document.getElementById(id);
for (var i = 0; i < lstdatabase.options.length; i++) {
if (lstdatabase.options[i].selected) {
if (retval == "") {
retval = lstdatabase.options[i].value;
}
else {
retval = retval + ',' + lstdatabase.options[i].value;
}
}
}
return retval;
}

Related

How to manipulate selected option's value to be the same as option text with JavaScript

I have this dynamic HTML / JavaScript form that is working great, but I found that when I click submit it is bringing over the value of the option as its index and not as the text within the option.
I have tried altering the JavaScript code but can not seem to figure out how to resolve this.
HTML
<!-- Category -->
<label for="type">Category<span class="required-input"> *</span></label>
<select id="type" name="type" onchange="ChangeTypeList()">
<option value="">--Select--</option>
<option value="Order Inquiry">Order Inquiry</option>
<option value="Product Inquiry">Product Inquiry</option>
</select>
<!-- Sub Category -->
<label for="reason">Sub Category</label>
<select id="reason" name="reason"></select>
JavaScript
var reasons = {};
reasons['Order Inquiry'] = ['Order Status','Order Issue', 'X'];
reasons['Product Inquiry'] = ['Product Weight', 'Product Quality'];
function ChangeTypeList() {
var typeList = document.getElementById("type");
var reasonsList = document.getElementById("reason");
var reasonsType = typeList.options[typeList.selectedIndex].value;
while (reasonsList.options.length) {
reasonsList.remove(0);
}
var decisions = reasons[reasonsType];
if (decisions) {
var i;
for (i = 0; i < decisions.length; i++) {
var decision = new Option(decisions[i], i);
reasonsList.options.add(decision);
// console.log('decision', decision);
}
}
}
When I select the first Category option 'Order Inquiry' and console.log:
console.log('decision', decision);
I see the following in the Console for the Sub Categories:
<option value="0">Order Status</option>
<option value="1">Order Issue</option>
<option value="2">X</option>
Ideally I want to see this is the Console for the Sub Categories:
<option value="Order Status">Order Status</option>
<option value="Order Issue">Order Issue</option>
<option value="X">X</option>
You need to pass decisions[i] as second parameter in Option.
Syntax:new Option(text, value, defaultSelected, selected); More details Option
var reasons = {};
reasons['Order Inquiry'] = ['Order Status','Order Issue', 'X'];
reasons['Product Inquiry'] = ['Product Weight', 'Product Quality'];
function ChangeTypeList() {
var typeList = document.getElementById("type");
var reasonsList = document.getElementById("reason");
var reasonsType = typeList.options[typeList.selectedIndex].value;
while (reasonsList.options.length) {
reasonsList.remove(0);
}
var reason = document.getElementById('reason');
var decisions = reasons[reasonsType];
if (decisions) {
var i;
for (i = 0; i < decisions.length; i++) {
//This line is changed
var decision = new Option(decisions[i], decisions[i]);
reasonsList.options.add(decision);
console.log('decision', decision);
}
}
}
<label for="type">Category<span class="required-input"> *</span></label>
<select id="type" name="type" onchange="ChangeTypeList()">
<option value="">--Select--</option>
<option value="Order Inquiry">Order Inquiry</option>
<option value="Product Inquiry">Product Inquiry</option>
</select>
<!-- Sub Category -->
<label for="reason">Sub Category</label>
<select id="reason" name="reason"></select>
option HTML element has a value and text attribute.
var options = document.getElementById("dropdown").children;
for (var i = 0; i < options.length; i++) {
options[i].value = options[i].text;
}
<select id="dropdown">
<option value="0">A</option>
<option value="1">B</option>
<option value="2">C</option>
</select>

1st dropdown name selection displays email value in 2nd dropdown

I have 2 drop-downs.
The drop-downs are dynamically populated.
What works: If name1 (drop-down1) is selected then email1 (drop-down2) is selected. (the js works).
What's not working: After selecting name1, if I select name4 email2 is displayed. What's happening is drop-down2 is going in numbered order rather than what's selected in drop-down1 order.
What should happen: The name selected should display the email that corresponds with that name. Example: name1 = email1, name2 = email2, name3 = email3, name4 = email4, name5 = email5, etc.
HTML
<select id="names" name="names" onchange="change(this.value);">
<option value="0"></option>
<option value="name1">name1</option>
<option value="name2">name2</option>
<option value="name3">name3</option>
<option value="name4">name4</option>
<option value="name5">name5</option>
</select>
<select id="emails" name="emails" onchange="change(this.value);">
<option value="0"></option>
<option value="email1">email1</option>
<option value="email2">email2</option>
<option value="email3">email3</option>
<option value="email4">email4</option>
<option value="email5">email5</option>
</select>
JS
function change(value) {
var names = document.getElementById('names');
var emails = document.getElementById('emails');
for (i = 0; i < names.length; i++) {
if (names.options[i].value == '0') {
emails.remove(i);
}
}
}
While you tagged a jquery this is a jquery solution
function change(el , value) {
var names = $('.select'),
selected_index = $(el).find('option:selected').index();
$('.select').not($(el)).find('option:eq('+selected_index+')').prop('selected',true);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="select" id="names" name="names" onchange="change(this , this.value);">
<option value="0"></option>
<option value="name1">name1</option>
<option value="name2">name2</option>
<option value="name3">name3</option>
<option value="name4">name4</option>
<option value="name5">name5</option>
</select>
<select class="select" id="emails" name="emails" onchange="change(this , this.value);">
<option value="0"></option>
<option value="email1">email1</option>
<option value="email2">email2</option>
<option value="email3">email3</option>
<option value="email4">email4</option>
<option value="email5">email5</option>
</select>
Steps:
1- don't forget to include jquery
2- give both of your <select> a class class="select"
3- your function will be change(el , value)
4- use the function like onchange="change(this , this.value);"
Try
function change(value){
var emails = document.getElementById('emails');
var emailValue = value.replace("name", "email");
for(var i = 0; i < emails.length; i++){
if(emails.options[i].value == emailValue){
emails.options[i].selected = true;
}
else {
emails.options[i].selected = false;
}
}
}
I think that should work.

Concatenating multiple menu selections into string with all possible variations

I have found here an answer to a question about concatenating menu selection to string using javascript.
I wonder if is it possible to change the select elements to multiple to create all possible combinations from selected values?
<form>
<input form="form" type="hidden" name="product_data[product]" id="product_description_product" value="{$product_data.product}" />
<script type='text/javascript'>
$("#product_description_product_1, #product_description_product_2, #product_description_product_3").change(function(){
concatenated_string = $("#product_description_product_1").val() +
$("#product_description_product_2").val() +
$("#product_description_product_3").val();
$("#product_description_product").val(concatenated_string);
})
</script>
<select size="5" multiple="multiple" id="product_description_product_1">
<optgroup label="Box size">
<option value="Extra small">Extra small</option>
<option value="Small">Small</option>
<option value="Medium">Medium</option>
<option value="Large">Large</option>
<option value="Extra Large">Extra Large</option>
</optgroup>
</select>
<select size="5" multiple="multiple" id="product_description_product_2">
<optgroup label="Speciality">
<option value="organic">organic</option>
<option value="seasonal">seasonal</option>
<option value="locally grown">locally grown</option>
<option value="exotic">exotic</option>
<option value="gourmet">gourmet</option>
</optgroup>
</select>
<select size="5" multiple="multiple" id="product_description_product_3">
<optgroup label="Type of box">
<option value="veg box">veg box</option>
<option value="fruit box">fruit box</option>
<option value="fruit & veg box">fruit & veg box</option>
</optgroup>
</select>
</form>
If I select for example:
from first select element: Small, Medium
from second select element: organic, gourmet
from third select element: fruit box
return me different strings with all possible combinations
Small organic fruit box
Medium organic fruit box
Small gourmet fruit box
Medium gourmet fruit box
Why don't you use array to save the values?
A simple way would create 3 arrays:
var itemsBoxSize;
var itemsSpeciality;
var itemsTypeBox;
So, when user select an item, adds it to the array. For example:
itemsBoxSize.push("Small");
Finally, you access all arrays:
for (i = 0; i <= itemsBoxSize.length; i++) {
var resultString = itemsBoxSize[i] + " " + itemsSpeciality[i] + itemsTypeBox[i];
}
Something like that!
I'm not sure if it's correct, but it's on the right way:
Note: it is still a little bit manual, but you can try to automate it.
HTML:
<div id="result"></div>
<form id="optionsForm">
<select size="5" multiple="multiple" id="boxSize">
<optgroup label="Box size">
<option value="Extra small">Extra small</option>
<option value="Small">Small</option>
<option value="Medium">Medium</option>
<option value="Large">Large</option>
<option value="Extra Large">Extra Large</option>
</optgroup>
</select>
<select size="5" multiple="multiple" id="speciality">
<optgroup label="Speciality">
<option value="organic">organic</option>
<option value="seasonal">seasonal</option>
<option value="locally grown">locally grown</option>
<option value="exotic">exotic</option>
<option value="gourmet">gourmet</option>
</optgroup>
</select>
<select size="5" multiple="multiple" id="typeBox">
<optgroup label="Type of box">
<option value="veg box">veg box</option>
<option value="fruit box">fruit box</option>
<option value="fruit & veg box">fruit & veg box</option>
</optgroup>
</select>
</form>
JQUERY:
$(document).ready(function() {
// It also is used to clear the array
function initItems() {
items["boxSize"] = [];
items["speciality"] = [];
items["typeBox"] = [];
}
var items = [];
initItems();
// When user selects items
$("#optionsForm").change(function() {
initItems(); // Clear items
$("select :selected").each(function(i, selected) {
var selectId = $(this).closest("select").attr("id");
items[selectId].push($(selected).text());
});
showResult();
});
function showResult() {
var s = "";
var highestLenght = getHighestLenght();
var partialLength;
for (i = 0; i < highestLenght; i++) {
// BOX SIZE
partialLength = items["boxSize"].length;
if (partialLength >= highestLenght) {
s += items["boxSize"][i] + " ";
} else {
s += items["boxSize"][partialLength - 1] + " ";
}
// SPECIALITY
partialLength = items["speciality"].length;
if (partialLength >= highestLenght) {
s += items["speciality"][i] + " ";
} else {
s += items["speciality"][partialLength - 1] + " ";
}
// TYPE BOX
partialLength = items["typeBox"].length;
if (partialLength >= highestLenght) {
s += items["typeBox"][i] + " ";
} else {
s += items["typeBox"][partialLength - 1] + " ";
}
s += "<br>";
}
$('#result').html(s);
}
// What is the highest amount of elements?
function getHighestLenght() {
var highestValues = [];
highestValues.push(items["boxSize"].length);
highestValues.push(items["speciality"].length);
highestValues.push(items["typeBox"].length);
var highest = Math.max.apply(null, highestValues);
return highest;
}
})

Dynamically adding textbox in Html

function change() {
var select = document.getElementById("slct");
var divv = document.getElementById("container");
var value = select.value;
for (i = 0; i <value; i++) {
toAppend += "<input type='textbox' >";
}
divv.innerHTML=toAppend;`enter code here`
return;
}
I Have this code and I am calling it by dropdown menu
<select id="slct" onchange="change();">
<option value="0"> select value </option>
<option value="1"> 1 </option>
<option value="2"> 2 </option>
<option value="3"> 3 </option>
but its not showing anything
Declare var toAppend='' before the for loop

javascript selectIndex right value

I have two possible dropdown list that I'm working with. The first one looks like:
<select id="drop1" name="drop1">
<option value="">Select</option>
<option value="1">January</option>
<option value="2">February</option>
...
</select>
<input type="text" value="1" onclick="set(this.value);" />
and the second one looks like
<select id="drop2" name="drop2">
<option value="1">January</option>
<option value="2">February</option>
...
</select>
<input type="text" value="1" onclick="set(this.value);" />
How can I make sure that if the value chosen in set(this.value) is = 1 (January) for instance, I will end up selecting January and not -- neither Feb.
Your'll need to iterate over the options of your <select> until you find one whose value is 1:
function selectOptionWithValue(select, value) {
value = "" + value;
var options = select.options;
for (var i = 0, len = options.length; i < len; ++i) {
if (options[i].value == value) {
select.selectedIndex = i;
return;
}
}
}
<input type="text" value="1"
onclick="selectOptionWithValue(document.getElementById('drop1'), this.value);">

Categories

Resources