Get selected values from 5 combo boxes - javascript

I have 3 drop downs, but it can change. It is dynamic drop down
How can I get all selected values in those drop downs?

This is an explanation of my comment..
Run the snippet to check it in action
var combos = document.querySelectorAll('[name^="select"]');
function getvalues() {
// Clear shown data
console.clear();
for (var i=0; i < combos.length; i++) {
// Get selected option value
var option = combos[i].options[combos[i].selectedIndex];
// Show options
console.log(combos[i].name + " :: " + option.value + " : " + option.text);
}
}
<select name="select-1">
<option value="1" selected>First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
<select name="select-2">
<option value="1">First</option>
<option value="2" selected>Second</option>
<option value="3">Third</option>
</select>
<select name="select-3">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3" selected>Third</option>
</select>
<button onclick="getvalues()">Get values</button>

Related

2 Select Boxes - Select Box 1 (A,B,C...) fills Select Box 2, doesn't work properly

I would like to have the output in select box 2 in such a way that if I choose something with B in select box 1, everything that begins with B in select box 1 is output. At the moment only one is issued and the others are not
$('#select1').on('change', () => {
$('#select2 option').hide();
$('#select2 option[value^="' + $('#select1').val() + '" ]').show();
}).trigger('change');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="standard" size="1" id="select1">
<option value="0">A</option>
<option value="1">B</option>
<option value="2">C</option>
<option value="3">D</option>
<option value="4">E</option>
<option value="5">F</option>
<option value="6">G</option>
<option value="7">H</option>
<option value="8">I</option>
<option value="9">J</option>
<option value="10">K</option>
<option value="11">L</option>
<option value="12">M</option>
</select>
<select name="standard" size="1" id="select2">
<option value="0" style="">Aal in Aspik</option>
<option value="1" style="display: none;">Bierwurst</option>
<option value="2" style="display: none;">Berliner (Faschingskrapfen)</option>
<option value="3" style="display: none;">Auberginenröllchen auf Tomaten-Zimt-Sugo</option>
</select>
Since your selector #select2 option[value^="' + $('#select1').val() + '" ] will only match one options, so the other options that have greater value still not be showed. You could try to use jQuery's filter
$('#select1').on('change', () => {
var value1 = $('#select1').val();
var option2 = $('#select2 option');
$('#select2').val(value1).change();
option2.hide();
option2.filter(function() {
return parseInt($(this).val()) >= parseInt(value1);
}).show();
}).trigger('change');
See demo here
Your issue is here:
[value^="' + $('#select1').val() + '" ]
If you debug select val, you'll see it's 1 for B as it takes the option value:
<option value="1">B</option>
To compare texts, you need to get the text of the current selected option, eg:
$('#select1 option:selected').text()
you can then use .filter to compare this with the first letter of each option in the second select:
$('#select2 option').filter((i,e)=> $(e).text().substr(0,1) == $('#select1 option:selected').text()).show();
Updated snippet:
$('#select1').on('change', () => {
$('#select2 option').hide();
$('#select2 option').filter((i,e)=> $(e).text().substr(0,1) == $('#select1 option:selected').text()).show();
}).trigger('change');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="standard" size="1" id="select1">
<option value="0">A</option>
<option value="1">B</option>
<option value="2">C</option>
<option value="3">D</option>
<option value="4">E</option>
<option value="5">F</option>
<option value="6">G</option>
<option value="7">H</option>
<option value="8">I</option>
<option value="9">J</option>
<option value="10">K</option>
<option value="11">L</option>
<option value="12">M</option>
</select>
<select name="standard" size="1" id="select2">
<option value="0" style="">Aal in Aspik</option>
<option value="1" style="display: none;">Bierwurst</option>
<option value="2" style="display: none;">Berliner (Faschingskrapfen)</option>
<option value="3" style="display: none;">Auberginenröllchen auf Tomaten-Zimt-Sugo</option>
</select>

How can I get the latest HTML tags of a changeable elements, like Select, Checkbox, Input in JS/Jquery?

I need to get the HTML tags of the changeable element so that I can pass them to create a PDF. But, whenever I use element.innerHTML or element.html(), I get the HTML tags generated after page load but not after I made the changes.
In HTML:
<select id="testSelect">
<option id="no">-- not selected --</option>
<option id="one" selected>1</option>
<option id="two">2</option>
</select>
In JS:document.getElementById("testSelect").innerHTML
It returns:
"
<option id="no">-- not selected --</option>
<option id="one" selected="">1</option>
<option id="two">2</option>
"
And now if I manually change the value to 2, then
In JS:
document.getElementById("testSelect").value
"2"
as you can see the value is changed. But, the HTML tags won't change as
In JS:
document.getElementById("testSelect").innerHTML
"
<option id="no">-- not selected --</option>
<option id="one" selected="">1</option>
<option id="two">2</option>
"
Still, I get the old tags. Instead, I want something like this.
"
<option id="no">-- not selected --</option>
<option id="one">1</option>
<option id="two" selected="">2</option>
"
I made this script for you hope it helps you!
var selectBox=document.querySelector("#testSelect");
selectBox.addEventListener("change", function(){
const selectBoxOptions=selectBox.querySelectorAll("option");
selectBoxOptions.forEach((option)=>{
option.removeAttribute("selected");
});
detectOptionObjectByValue(this, this.value).setAttribute("selected", "selected");
});
function detectOptionObjectByValue(selectBox, value){
const options=selectBox.querySelectorAll("option");
let pos=0, obj=false;
options.forEach(function(option){
option.value==value?obj=options[pos]:0;
pos++;
});
return obj;
}
<select id="testSelect">
<option id="no">-- not selected --</option>
<option id="one" selected>1</option>
<option id="two">2</option>
</select>
You can make a function which will iterate through all options and set all the selected attributes to false
$('select option[value=' + i + ']').attr("selected",false);
Then based on the value selected set the attribute to true
$('select option[value=' + this.value + ']').attr("selected",true);
const dropdownElement = document.getElementById('testSelect')
dropdownElement.onchange = function () {
clearSelected()
$('select option[value=' + this.value + ']').attr("selected",true);
console.log("value selected: " + this.value);
console.log("html: " + dropdownElement.innerHTML)
};
// set all the options to unselected
function clearSelected(){
var elements = dropdownElement.options;
for(var i = 0; i < elements.length; i++){
$('select option[value=' + i + ']').attr("selected",false);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="testSelect">
<option id="no" value="0">-- not selected --</option>
<option id="one" value="1" selected>1</option>
<option id="two" value="2">2</option>
</select>
On jQuery site you have similar question explained:
https://learn.jquery.com/using-jquery-core/faq/how-do-i-get-the-text-value-of-a-selected-option/
$(function(){
$('#select').change(function(){
$('#output-value').text($(this).val());//get value
$('#output-element').text($(this).find('option:selected').text());//get text of selected element
$(this).find('option').each(function(){
$(this).attr('selected', $(this).is('option:selected')); //adds and removes selected attribute
});
$('#output-html').text($(this).html());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="select" >
<option>--</option>
<option value="1" >1 val</option>
<option value="2" >2 val</option>
<option value="3" >3 val</option>
</select>
<br/>
Value
<div id="output-value" ></div>
Element
<div id="output-element" ></div>
HTML
<div id="output-html"></div>

Make Select Menu Revert on Cancel Dialogue

I am making a system in which a user can change a select drop down and it will give them a prompt to ensure they want to take the action. Here is my code:
function changeResStatus(str1) {
var id = str1;
var status = document.getElementById("resstatus" + id).value;
var r = confirm("Change status for ID # " + id + " to " + status + "?");
if (r == true) {
console.log ("change made");
}else{
console.log ("change not made");
}
}
In the event the change is not made, I would like the select menu to go back to the previous option it was before the user attempted to change it. How would I do that?
please try this one.
$(document).on('change','.mydropdown',function(){
var previousValue = $(this).attr("data-previousvalue");
var r = confirm("Change status for");
if (r == true)
{
$(this).attr("data-previousvalue",$(this).val())
}
else
{
$(this).val($(this).attr("data-previousvalue"));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="mydropdown" data-previousvalue="0">
<option value="0">select something</option>
<option value="1">something 1</option>
<option value="2">something 2</option>
<option value="3">something 3</option>
</select>
<select class="mydropdown" data-previousvalue="0">
<option value="0">select something</option>
<option value="101">something 101</option>
<option value="102">something 102</option>
<option value="103">something 103</option>
</select>
<select class="mydropdown" data-previousvalue="0">
<option value="0">select something</option>
<option value="201">something 201</option>
<option value="202">something 202</option>
<option value="202">something 203</option>
</select>

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;
}
})

jQuery remove SELECT options based on another SELECT selected (Need support for all browsers)

Say I have this dropdown:
<select id="theOptions1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
I want it so that when the user selects 1, this is the thing that the user can choose for dropdown 2:
<select id="theOptions2">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
Or if the user selects 2:
<select id="theOptions2">
<option value="a">a</option>
<option value="b">b</option>
</select>
Or if the user selects 3:
<select id="theOptions2">
<option value="b">b</option>
<option value="c">c</option>
</select>
I tried the code posted here:
jQuery disable SELECT options based on Radio selected (Need support for all browsers)
But it doesn't work for selects.
Please help!
Thank you!
UPDATE:
I really like the answer Paolo Bergantino had on:
jQuery disable SELECT options based on Radio selected (Need support for all browsers)
Is there anyway to modify this to work with selects instead of radio buttons?
jQuery.fn.filterOn = function(radio, values) {
return this.each(function() {
var select = this;
var options = [];
$(select).find('option').each(function() {
options.push({value: $(this).val(), text: $(this).text()});
});
$(select).data('options', options);
$(radio).click(function() {
var options = $(select).empty().data('options');
var haystack = values[$(this).attr('id')];
$.each(options, function(i) {
var option = options[i];
if($.inArray(option.value, haystack) !== -1) {
$(select).append(
$('<option>').text(option.text).val(option.value)
);
}
});
});
});
};
This works (tested in Safari 4.0.1, FF 3.0.13):
$(document).ready(function() {
//copy the second select, so we can easily reset it
var selectClone = $('#theOptions2').clone();
$('#theOptions1').change(function() {
var val = parseInt($(this).val());
//reset the second select on each change
$('#theOptions2').html(selectClone.html())
switch(val) {
//if 2 is selected remove C
case 2 : $('#theOptions2').find('option:contains(c)').remove();break;
//if 3 is selected remove A
case 3 : $('#theOptions2').find('option:contains(a)').remove();break;
}
});
});
And the beautiful UI:
<select id="theOptions1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br />
<select id="theOptions2">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
You can add classes to your <option>s to store which go with each value of #theOptions1:
<select id="theOptions2">
<option value="a" class="option-1 option-2">a</option>
<option value="b" class="option-1 option-2 option-3">b</option>
<option value="c" class="option-1 option-3">c</option>
</select>
then do this:
$(function() {
var allOptions = $('#theOptions2 option').clone();
$('#theOptions1').change(function() {
var val = $(this).val();
$('#theOptions2').html(allOptions.filter('.option-' + val));
});
});
For the record you can NOT remove options in a select list in Internet Explorer.
try this. this will definitely work
$(document).ready(function () {
var oldValue;
var oldText;
var className = '.ddl';
$(className)
.focus(function () {
oldValue = this.value;
oldText = $(this).find('option:selected').text();
})
.change(function () {
var newSelectedValue = $(this).val();
if (newSelectedValue != "") {
$('.ddl').not(this).find('option[value="' + newSelectedValue + '"]').remove();
}
if ($(className).not(this).find('option[value="' + oldValue + '"]').length == 0) { // NOT EXIST
$(className).not(this).append('<option value=' + oldValue + '>' + oldText + '</option>');
}
$(this).blur();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<form action="/Home/Ex2" method="post">
<select class="ddl" id="A1" name="A1">
<option value="">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
<hr />
<select class="ddl" id="A2" name="A2">
<option value="">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
<hr />
<select class="ddl" id="A3" name="A3">
<option value="">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
<hr />
<select class="ddl" id="A4" name="A4">
<option value="">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
<hr />
<input type="submit" name="submit" value="Save Data" id="btnSubmit" />
</form>
Actually, using the code below will remove a dropdown option just fine in IE, as long as it is not the selected option (it will not work on "a" without deselecting that option first):
var dropDownField = $('#theOptions2');
dropDownField.children('option:contains("b")').remove();
You just run this to remove whatever option you want to remove under a conditional statement with the first group (theOptions1) - that if one of those is selected, you run these lines:
var dropDownField = $('#theOptions2');
if ($('#theOptions1').val() == "2") {
dropDownField.children('option:contains("c")').remove();
}
if ($('#theOptions1').val() == "3") {
$("#theOptions2 :selected").removeAttr("selected");
$('#theOptions2').val('b');
dropDownField.children('option:contains("a")').remove();
}
-Tom

Categories

Resources