How to get optgroup value from Javascript? - javascript

<html>
<body>
<select name="lstparameters">
<optgroup value="100" label="Swedish Cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
</optgroup>
<optgroup value="101" label="German Cars">
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</optgroup>
</select>
</body>
</html>
How to get optgroup values from javascript?I want to get 100 and 101 values.

For those like me wanting to get the optgroup label of the selected option, do this:
document.querySelector('select[name="lstparameters"] option:checked').parentElement.label
Having a select with an id simplifies the selector:
document.querySelector('#lstparameters option:checked').parentElement.label

You can get the optgroup elements and read the value attribute
var values = Array.from(document.querySelectorAll('select[name="lstparameters"] > optgroup')).map(el => el.getAttribute('value'));
alert(values);
//if you want old browser support
var values = [].slice.call(document.querySelectorAll('select[name="lstparameters"] > optgroup')).map(function(el) {
return el.getAttribute('value')
});
alert(values);
<select name="lstparameters">
<optgroup value="100" label="Swedish Cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
</optgroup>
<optgroup value="101" label="German Cars">
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</optgroup>
</select>

You can use the .closest() function to determine the selected optgroup
$(function() {
var selected = $('select option:selected');
alert(selected.closest('optgroup').attr('value'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<select name="lstparameters">
<optgroup value="100" label="Swedish Cars">
<option value="volvo">Volvo</option>
<option value="saab" selected>Saab</option>
</optgroup>
<optgroup value="101" label="German Cars">
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</optgroup>
</select>
</body>
</html>

#Arun P Johny shows already some ways which are nice and simple.
I just want to provide some other methods.
For really old browsers (< IE9):
var dropdown = document.getElementsByName('lstparameters')[0];
var optgroups = dropdown.getElementsByTagName('optgroup');
var results = [];
for(var i = 0; i < optgroups.length; i++) {
results.push(optgroups[i].getAttribute('value'));
}
alert(results);
And another option with arrow functions and array prototype map:
var results = [].map.call(document.querySelectorAll('select optgroup'), x => { return x.getAttribute('value') });
alert(results);
Update:
To get the value by label you can either add the label to yours query selector (optgroup[label="Swedish Cars"]) or for the for loop method see this:
var dropdown = document.getElementsByName('lstparameters')[0];
var optgroups = dropdown.getElementsByTagName('optgroup');
for(var i = 0; i < optgroups.length; i++) {
if (optgroups[i].getAttribute('label') == 'Swedish Cars') {
alert(optgroups[i].getAttribute('value'));
return;
};
}
alert(results);

Related

How to track the select option is deselect and and grab the deselect option value in jquery

Below is the example of the code for the scenario.
<select class="car" multiple name="cars">
<option value="volvo">Volvo</option>
<option value="honda" selected>honda</option>
<option value="opel" selected>Opel</option>
<option value="audi">Audi</option>
</select>
Suppose if deselect the honda, how would i know that this particular option is deselected and how i will grab that option value in jquery.
Thanks in advance
You can keep some variables and filter out those accordingly.
and in JS, you can handle these variables in the events
Here is the snippet, Hopefully you were looking for the same.
var prevValues = [];
var currentValues = [];
$(document).ready(function() {
currentValues = $('.car').val();
})
$('.car').on('change', function() {
prevValues = [...currentValues];
currentValues = $('.car').val();
let newlyAdded = currentValues.filter(x=> !prevValues.includes(x))[0];
let newlyRemoved = prevValues.filter(x=> !currentValues.includes(x))[0];
if(newlyAdded) {
console.log('Added item', newlyAdded);
}
if( newlyRemoved) {
console.log('Removed Item', newlyRemoved);
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="car" multiple name="cars">
<option value="volvo">Volvo</option>
<option value="honda" selected>honda</option>
<option value="opel" selected>Opel</option>
<option value="audi">Audi</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 Show Multiple select option value

I am trying to get (or show) values from Multiple Select using only Javascritpt. Let's say, the user can select multiple options from here, and when they click the 'Show Select' button they can see what are the values of these options.
I took the idea about 'selected' attribute from here
But, the code didn't work. Any help?
<select id ="selectOptions" name="cars" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<button onclick="myFunction()">Show Selects</button>
<script>
function myFunction()
{
var numOfOptions = document.getElementById("slectOptions").options.length;
var n=0;
for (n=0; n<numOfOptions; n++)
{
// I tried to use a for loop that will go around from option 0 to 3,
//and through 'selected' attribute wanted to check the condition if the option is selected then only show the values
// I still couldn't figure out if the loop is working at all
if (document.getElementById("slectOptions")[n].selected)
{
var x = document.getElementById("slectOptions").value;
window.alert(x);}
}
}
Just use
var select = document.getElementById("selectOptions");
console.log(select.selectedOptions);
Iterate over the options and check checked property. Although there is a simple type in your selector where missing e in the string.
function myFunction() {
var options = document.getElementById("selectOptions").options;
for (var n = 0; n < options.length; n++) {
if (options[n].selected) {
console.log(options[n].value);
}
}
}
<select id="selectOptions" name="cars" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<button onclick="myFunction()">Show Selects</button>
Or use readonly selectedOptions property to get the collection of selected options.
function myFunction() {
var options = document.getElementById("selectOptions").selectedOptions;
for (var n = 0; n < options.length; n++) {
console.log(options[n].value);
}
}
<select id="selectOptions" name="cars" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<button onclick="myFunction()">Show Selects</button>
<!DOCTYPE html>
<html>
<script>
function eraseText() {document.getElementById("txtChoices").value = "";
}
function SetMulti() {var txtChoices = document.getElementById("txtChoices"); txtChoices.value += document.getElementById("choiceNames").value;
}
</script>
</head>
<body>
<input type="text" id="txtChoices" readonly="readonly" placeholder="Multiple choice"/></br>
"Variable" Choice dropdown:
</br>
<select multiple="" name="choiceNames" id="choiceNames">
<option value="Long, ">Long, </option>
<option value="Short, ">Short, </option>
<option value="Red, ">Red, </option>
<option value="Curly, ">Curly, </option>
<option value="Straight, ">Straight, </option>
</select>
<button onclick="SetMulti()">Add</button>
<button onclick="eraseText()">Reset</button>
</body>
</html>

Get only newly added and removed option from HTML select with multiple attribute?

My question seem easy but I cannot figure it out.
Fiddle Demo
HTML:
<select multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
jQuery:
var choiceArr = [];
$('select').change(function () {
var text = $(this).find('option:selected').text();
choiceArr.push(text);
console.log(choiceArr);
});
So currently, if I choose Volvo and Saab the result will be:
["Volvo", "VolvoSaab"]
My expected result is:
["Volvo", "Saab"]
When I remove Saab from the selections, the result will be:
["Volvo", "VolvoSaab", "Volvo"]
My expected result is:
["Volvo"]
So how can I achieve it?
Demo
Try
var choiceArr = [];
$('select').change(function () {
choiceArr = $(this).find('option:selected').map(function () {
return $(this).text();
}).get();
alert(choiceArr);
});
Try this
<select multiple="multiple" id="select1">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<label id="result"></label>
Js
$('select').change(function () {
var selValues = $.map($("#select1 option:selected"), function (temp) {
return $(temp).text();
});
$("#result").text(selValues.join(", "));
});
Fiddle

Javascript - show TextField when select choice is

I'm new in JavaScript and I have following issue.
In my HTML code is ordinary SELECT
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
I need to show TextFied under the SELECT only when user select choice Audi.
<input type="text" name="something">
What is the best way to do that?
Start using JQuery (JQuery).
Here is the javascript:
$(document).ready(function(){
// On Select option changed
$("#someId").change(function(){
// Check if current value is "audi"
if($(this).val() === "audi"){
// Show input field
$("#textInputId").show(); //This changes display to block
}else{
// Hide input field
$("#textInputId").hide();
}
});
});
Here is the HTML
<select id="someId">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<input type="text" style="display:none;" id="textInputId" name="someName"/>
Here is the example on JSFiddle:
EXAMPLE
Do this:
<select id="select">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<input type="hidden" id="txt" name="something">
And do something like this:
select.onchange=function(){
if(select.value=="audi"){
txt.type="text";
}
}
Demo:http://jsfiddle.net/943xQ/
you can achieve it easily using jquery like this:
here is the Html:
<select id="cars">
<option value="-1">Select One</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
and text field:
<input type="text" name="something" id="txtCar" style="display:none;">
$('select#cars').change(function(){
if($(this).val() == "audi")
{
$('input#txtCar').show();
}
});
Here is the DEMO
Place this at the bottom of the page (provided you already have included jquery into this page):
<script>
$('select').change(function () {
if ($(this).val() == 'audi') {
$(this).parent().append('<input type="hidden" name="something">');
}
});
</script>
You can attach the onchange event at select tag and can perform the action you want. Something like
HTML
<div id="result">
<select id="mySelect">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</div>
JS
var select = document.getElementById("mySelect");
select.addEventListener("change", function() {
if(this.options[this.selectedIndex].value == 'audi'){
var input = document.createElement('input');
input.type="text";
input.id="txt";
input.name="something";
document.getElementById('result').appendChild(input);
}
});
DEMO
Given the posted HTML, in which you use no specific identifiers (class or id) to identify the relevant elements, and given that you've not specified the availability of any JavaScript library, I'd suggest the following 'plain' JavaScript solution:
function showInputWhen(evt,val){
var el = evt.target;
el.nextElementSibling.style.display = el.value.toLowerCase() == val.toLowerCase() ? 'inline-block' : 'none';
};
var selectEl = document.querySelector('select');
selectEl.addEventListener('change', function(e){
showInputWhen(e,'audi');
});
JS Fiddle demo.
References:
ChildNode.nextElementSibling compatibility.
document.querySelector() compatibility.
EventTarget.addEventListener() compatibility.

Categories

Resources