Get the values of all select options on change event javascript - javascript

I want to know all the values of a select element once the change event is recorded on it.
Code is like this:
PHP
<select name='variant' class='variantsselect' onchange='on(this.value)'>
<option value='a'>a</option>
<option value='a'>a</option>
</select>
JAVASCRIPT
function on(value){
alert(value); //This gives me selected value
};
I need values a & b when change event is recorded on select element. Can someone help?

<select name='variant' class='variantsselect' onchange="javascript:valueselect(this)">
function valueselect(sel) {
var value = sel.options[sel.selectedIndex].value;
alert(value)
}
EDIT:
<select name='variant' id='variant' class='variantsselect' onchange="javascript:displayResult()">
function displayResult() {
var x = document.getElementById("variant");
var i;
var txt = "Text: ";
for (i = 0; i < x.length; i++) {
txt = txt + "\n" + x.options[i].text;
}
alert(txt);
}

You can store the last selected value in a variable and overwrite the variable with the new selected value at the end of your function. When the function is called the variable will = to the last option selected (If you don't set a default value the variable will be empty on the first call)
Click Here For Demo
OR
This will work for a simple hide/show select without having to remember the previous selection.
The hide/show content have a class name of HideShow, this class name css display is set to none. When you change the option it will loop through all elements using the class name HideShow to compare the selected value with the id of the element, if they match it will set the style display to block }else{ set style display to none.
Demo
function HideShow(Selection){
var HScontent=document.getElementsByClassName('HideShow');
for(var i=0; i<HScontent.length; i++){
if(HScontent[i].id==Selection){
HScontent[i].style.display="block";
}else{
HScontent[i].style.display="none";
}
}
}
.HideShow{display:none;}
<select onchange="HideShow(this.value);">
<option value="cars">Cars</option>
<option value="bikes">Bikes</option>
<option value="buses">Buses</option>
</select>
<div id="cars" class="HideShow">Cars content.....</div>
<div id="bikes" class="HideShow">Bikes content....</div>
<div id="buses" class="HideShow">Buses content....</div>
If you don't understand something in the demo, leave a comment below and I will try get back to you as soon as possible.
I hope this helps. Happy coding!

Related

display a part of value in select option

I have a select drop-down with country and code. In drop-down option, for user experience and understanding i am displaying name of the country along with country code.
As a normal functionality when a user selects any value from the drop-down that value gets displayed inside the input like this
however i want that only the country code should get displayed like this
Part of my code
<select name="countrycode" class="form-control pf-country" id="countrycode">
<option data-countryCode="IN" value="91">Code</option>
<option data-countryCode="IN" value="91">India (+91)</option>
<option data-countryCode="US" value="1">USA (+1)</option>
<optgroup label="Other countries">
<option data-countryCode="DZ" value="213">Algeria (+213)</option>
<option data-countryCode="AD" value="376">Andorra (+376)</option>
</optgroup>
</select>
The entire code is available here
Can anyone please suggest how to do it.
As per my understanding, You can try this one. As this example providing exact output as you mentioned in your questions.
https://silviomoreto.github.io/bootstrap-select/examples/#selected-text
Basically we're trying to change innerText of selected-option. It can be achieved easily by adding onchange event listener to the select tag.
But there's a little problem, on changing innerText we lose previous value of innerText, solution by #KKK solves problem but leaves this little thing.
Following code handles problem in complete ways. We're adding data-innerText atribute with previous value of innerText and also id="previous" to identify it. Please check this demo.
function simpleTweak(select){
var previouslySelectedTag = document.getElementById('previous');
if(previouslySelectedTag!=undefined){
previouslySelectedTag.innerText = previouslySelectedTag.getAttribute('data-innerText');
previouslySelectedTag.setAttribute('id','');
}
var innerText = select.options[select.selectedIndex].innerText;
select.options[select.selectedIndex].setAttribute('data-innerText',innerText);
select.options[select.selectedIndex].setAttribute('id','previous');
var value="(+"+select.options[select.selectedIndex].value+")";
select.options[select.selectedIndex].innerText = value;
}
As I understood, you need to change the display text after selecting the option, is it? If so, you can do it like this.
You can set the selected index's text in onchange event. But it will reset the text in the option when you click the dropdown again. You may need to change it back if you prefer.
function displayCountryCode() {
var countrycode = document.getElementById("countrycode");
countrycode.options[countrycode.selectedIndex].text = '+' + countrycode.value;
}
<select name="countrycode" class="form-control pf-country" id="countrycode" onchange="displayCountryCode()">
<option data-countryCode="IN" value="91">Code</option>
<option data-countryCode="IN" value="91">India (+91)</option>
<option data-countryCode="US" value="1">USA (+1)</option>
<optgroup label="Other countries">
<option data-countryCode="DZ" value="213">Algeria (+213)</option>
<option data-countryCode="AD" value="376">Andorra (+376)</option>
</optgroup>
</select>
The following JavaScript code will change the text of the selected option when you select it and change it back when you select a different one.
It does this by saving the values of the country name and country number as HTML5 data attributes (option.dataset.countryName & option.dataset.countryNumber)
Doing it this way, you don't have to change the format of the HTML from what you provided in your post.
I used vanilla JavaScript, so it'll work with or without jQuery.
window.addEventListener('load', () => {
let select = document.getElementsByName('countrycode')[0]
let options = document.getElementsByTagName('option')
for (let i = 1; i < options.length; i++) {
let option = options[i]
let matches = option.innerText.match(/(.*?) (\(\+\d+\))/)
option.dataset.countryName = matches[1]
option.dataset.countryNumber = matches[2]
// Set the value in the collection again now that the object has been changed
options[i] = option
}
select.addEventListener('change', () => {
for (let i = 1; i < options.length; i++) {
let option = options[i];
option.innerText = option.dataset.countryName + ' '
option.innerText += option.dataset.countryNumber
}
let option = document.querySelector('option:checked')
if (option !== options[0]) {
option.innerText = option.dataset.countryNumber
}
})
})
There's also a demo at CodePen

When registering both onchange and onclick on a select, the click event is triggered twice

Goal: Have a select whose option have nested structure when user clicks on the select, but when user selects an option the option should be displayed "normally" (ie with no leading spaces).
Attempted solution using JS and Jquery: My JS is far from sophisticated so I apologize in advance :)
I attempted to use .on("change") and .on("click") to change the selected option value (by calling .trim() since I achieve the "nested" structure with ). I'm also storing the original value of the selected option because I want to revert the select menu to its original structure in case the user selects another option.
The problem: The function registered for .on("click") is called twice, thus the select value immediately resets itself to its original value.
I suspect there is a much, much easier solution using CSS. I will be happy to accept an answer that will suggest such solution.
JSFiddle: https://jsfiddle.net/dv6kky43/9/
<form>
<select id="select">
<option value=""></option>
<option value="a"> a</option>
<option value="b"> b</option>
</select>
</form>
<textarea id="output"/>
var orig;
var output = $("#output");
output.val("");
function onDeviceSelection(event){
output.val(output.val() + "\nonDeviceSelection");
var select = event.target;
orig = select.selectedOptions[0].text;
select.selectedOptions[0].text = select.selectedOptions[0].text.trim()
}
function resetDeviceSelectionText(event) {
output.val(output.val() + "\nresetDeviceSelectionText");
var select = event.target;
if (orig !== undefined){
select.selectedOptions[0].text = orig;
}
}
$("#select").on("change", onDeviceSelection);
$("#select").on("click", resetDeviceSelectionText);
If you are already using jQuery, why not utilize data function to store the original value. This way you will also be able to specify different nest levels.
(function($){
$(document).on('change', 'select', function(event) {
$(this).find('option').each(function(index, element){
var $option = $(element);
// Storing original value in html5 friendly custom attribute.
if(!$option.data('originalValue')) {
$option.data('originalValue', $option.text());
}
if($option.is(':selected')) {
$option.html($option.data('originalValue').trim());
} else {
$option.html($option.data('originalValue'));
}
})
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select id="select">
<option value=""></option>
<option value="a"> a</option>
<option value="b"> b</option>
</select>
</form>
Once caveat I see is, the selected option will appear trimmed on the list as well, if dropdown is opened after a previous selection has been made:
Will it still work for you?
Instead of keeping the state of the selected element i would simply go over all options and add the space if that option is not selected:
function onDeviceSelection(event){
// Update textarea
output.val(output.val() + "\nonDeviceSelection");
// Higlight the selected
const {options, selectedIndex} = event.target;
for(let i = 0; i < options.length; i++)
options[i].innerHTML = (i === selectedIndex ? "":" ") + options[i].text.trim();
}
$("#select").on("change", onDeviceSelection);
Note that you need to use innerHTML to set the whitespace...

Do dependent dropdown in html using javascript with value and text

I have already a dependent dropdown list in my html form by using only javascript, but when my php script returns values these are just numbered by the position of the text in an array. I would like to have both Value and Text the same value
Here is what I have so far:
SCRIPT IN HEAD TAG:
var my_variable=[
["dropA_opt1","dropA_opt2",dropA_opt3"],
["dropB_opt1","dropB_opt2",dropB_opt3"],
["dropC_opt1","dropC_opt2",dropC_opt3"]
];
function variable(idx) {
var f=document.my_form;
f.drop_nr_2.length=null;
for(var i=0; i<my_variable[idx].length; i++) {
f.drop_nr_2.options[i]=new Option(my_variable[idx][i], i);
}
}
SELECT for main DROPDOWN
<select name="drop_nr_1" onchange="my_variable(this.selectedIndex)">
<option value="" selected disabled></option>
<option value="value1">value1</option>
<option value="value2">value2</option>
</select>
SELECT for dependent DROPDOWN
<select name="drop_nr_2">
</select>
The code i have basically creates the options from the array index, but there is no value="" attribute. From that reason I am getting the array index back - but I need a value="same as the text".
In addition it would be nice to have always the first option in the 2nd dropdown selected and disabled with empty value (like in dropdown 1).
Much appreciate your help
When constructing <option> by using javascript object syntax.
var myOpt = new Option(lbl,val);
The first parameter is the label that user sees it having the second parameter is the value that will be used for this <option> internally.So just modify the constructor line a bit
f.drop_nr_2.options[i]=new Option(my_variable[idx][i], my_variable[idx][i]);
For second requirement add a condition for i===0 when it's true pass additional third parameter (wiz. selected) and make disabled property true
for(var i=0; i<my_variable[idx].length; i++) {
if(i===0){
f.drop_nr_2.options[i]=new Option(my_variable[idx][i], my_variable[idx][i],"selected");
f.drop_nr_2.options[i].disabled= true;
} else{
f.drop_nr_2.options[i]=new Option(my_variable[idx][i], my_variable[idx][i]);
}
}

jquery, get value of different select list

I have a lot of select list (hundreds) like this (they have all the same name and id (I think my problem comes from here... but I can't change it):
<select name="custom_element_grid_class" id="custom_element_grid_class" class="select-size">
<option value="normal">normal</option>
<option value="square">square</option>
<option value="wide">wide</option>
<option value="tall">tall</option>
</select>
I want to get value of each list when an user change the value. I made this script but it only works on my fist select list...
jQuery("#custom_element_grid_class").change(function(){
var element = jQuery(this);
var selected = element.find('option:selected');
var size = selected.val();
var sclass = size + " element isotope-item";
jQuery(element).closest('.element').attr('class',sclass);
});
How can I make it works for all my select form?
EDIT: each select list comes from an ajx call, that's the reason I've got the same ID, but only in the futur DOM.
You cannot have double ID's.
So my suggestion in calling a function by inline onchange in the select.
For example:
<select name="custom_element_grid_class" id="custom_element_grid_class" onchange="func(this)" class="select-size">
And then your function:
function func(el){
var element = el;
var size = element.value;
var sclass = size + " element isotope-item";
jQuery(element).closest('.element').attr('class', sclass);
};
Demo here
I would suggest adding a first option with no value, so that, as you say "when an user change the value" you can read in case he took the first value.
If you can help it avoid duplicate IDs in exchange for classes. If this isn't an option use an attribute selector. Modifying the above code slightly.
Document Ready
$(function()
{
$('[name=custom_element_grid_class]').change(function(){
var $element = $(this);
var size = $element.val();
var sclass = size + " element isotope-item";
$element.closest('.element').attr('class',sclass);
});
});
Fiddle

Select drop down html

I have a main select "main", and a list from 2 till 9, depending the situation, of more selects.
What if I want to change the value in all this secondary selects, with the same value that the main select?. So the main select will change more than 1 select at the same time:
So, I have got the main select:
<select name="main" id="main" onchange="document.getElementById('item').value = document.getElementById('main').value">
<option value = p>Please Select</option>
<option value = b>BOOK</option>
<option value = d>DVD</option>
</select>
And the next selects are made in php inside a loop, so I will have 2,3,4,5,..,9 selects depending the situation. Each of them with a different name (because I use this name in POST)
<select name=item_".$itemnumber." id="item">
<option value = p>Please Select</option>
<option value = b>BOOK</option>
<option value = d>DVD</option>
</select>
With this I want to have the possibility to select in one time the option for all the selects, but maintaining the possibility to change only some of the selects.
I made it work like that:
function changeValue(theElement) {
var theForm = theElement.form, z = 0;
for(z=0; z<theForm.length;z++){
if(theForm[z].id == 'item' && theForm[z].id != 'main'){
theForm[z].selectedIndex = theElement.selectedIndex;
}
}
}
But I dont know if thats the best way, I heard here that jQuery would be easier, so I would like to know how to make it in jQuery, please.
What I understand is, you have a <select> dropdown, and on change of the text in this one, you want to change the the selection in one or more of other dropdowns on your screen. Am I right?
If this is the case, then you have to have a javascript function and call this in the onchange of the <select>.
In this javascript function, you have to set the selected value of all the dropdowns you want.
If this is not what you want, Can you please rephrase your question and tell us what you exactly you want?
EDIT
function setElement()
{
var selectedValue = document.getElementById("main").value;
selectThisValue(document.getElementById("child1"), selectedValue);
selectThisValue (document.getElementById("child2"), selectedValue);
}
function selectThisValue(selectElement, val)
{
for ( var i = 0; i < selectElement.options.length; i++ )
{
if ( selectElement.options[i].value == val )
{
selectElement.options[i].selected = true;
return;
}
}
}
Call setElement() in your onchange of the main. This function gets the selected item from the main <select> and selects the items in the other dropdowns that have the same value.
You call the selectThisValue function once for every select you need to change.
Change the ids as per your code.
Never put the same id in all the select elements... ID is supposed to be unique for elements in a page.
change your html to look like
<select id="main" class="master">....</select>
<select id="test1" class="child">....</select>
<select id="test2" class="child">....</select>
<select id="test3" class="child">....</select>
<select id="test4" class="child">....</select>
Class attribute for multiple elements can be the same.
Your function needs to be modified to look like this
(i havent tested this, but should work..)
function changeValue(theElement) {
var theForm = theElement.form, z = 0;
for(z=0; z<theForm.length;z++){
if(theForm[z].className == 'child'){
theForm[z].selectedIndex = theElement.selectedIndex;
}
}
}
by the way, do the options inside these select boxes vary? if so, you'll have to match by value rather than index
EDIT: here's the code i wrote later.. modify it to suit your need
<html>
<head><title>select change cascade</title></head>
<body>
<select id="main" class="master"><option value="1">book</option><option value="2">cd</option></select>
<select id="test1" class="child"><option value="1">book</option><option value="2">cd</option></select>
<select id="test2" class="child"><option value="1">book</option><option value="2">cd</option></select>
<select id="test3" class="child"><option value="1">book</option><option value="2">cd</option></select>
<select id="test4" class="child"><option value="1">book</option><option value="2">cd</option></select>
<script type="text/javascript" src="./selectchange.js"></script>
</body>
</html>
and in selectChange.js
var main = document.getElementById("main");
main.onchange = function (){
sels = document.getElementsByTagName("select");
for(z=0; z<sels.length;z++){
if(sels[z].className == 'child'){
sels[z].selectedIndex = this.selectedIndex;
}
}
}
I don't see any question marks.
The only issue I see is that you should use .selectedIndex instead of .value.
jQuery solution:
$(".selectorClass").each(function(index, selectorToUpdate){
selectorToUpdate.selectedIndex = $('#main').selectedIndex;
});
Put this in a function and call that function for onchange.

Categories

Resources