Select drop down html - javascript

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.

Related

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...

Can't change html select selected value in javascript

I need to change the 'selected' attribute of a html option element within a select object using javascript.
I already tried this: Solution
This is what I have:
.cshtml
<div class="form-group form-group-default" id="divStateEUA">
<label>Estado</label>
<select id="listStateEUA" name="listStateEUA" data-init-plugin="select2" style="width: 100%">
#foreach (var state in ViewBag.EUAStates)
{
<option>#state</option>
}
</select>
</div>
javascript
<script>
$(document)
.ready(function () {
CheckState();
});
function CheckState() {
if (selectedText == 'Estados Unidos') {
var element = document.getElementById('listStateEUA');
element.value = 'Chicago';
}
}
</script>
rendered html:
And still not working. Any ideas?
You are missing value attribute in the option tag of select.
Modify your razor code to have value attribute in option tag, so that you can change the combo-box selection on basis of value :
#foreach (var state in ViewBag.EUAStates)
{
<option value="#state">#state</option>
}
and now in your jquery code, you should be able to do :
function CheckState() {
if (selectedText == 'Estados Unidos') {
$("#listStateEUA").val("Chicago");
}
}
You must provide a value for the options. Your JS is trying to set the select to the "Chicago" value, but none exists. <option>Chicago</option> vs <option value="Chicago">Chicago</option>
function CheckState() {
var element = document.getElementById('listStateEUA');
element.value = 'chicago';
}
CheckState();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Estado</label>
<select id="listStateEUA" name="listStateEUA">
<option value="nevada">nevada</option>
<option value="chicago">chicago</option>
<option value="arizona">arizona</option>
</select>
As Mike McCaughan suggested (thank you very much), since I'm using select2 plugin, it have a different way to get and set values.
$("#select").select2("val"); //get the value
$("#select").select2("val", "CA"); //set the value
Answer found here: select2 plugin get and set values

make a select dependent with js

I would like to do a select option dependent of another select, i saw there's a way using array with fixed values, but my array is reloaded every time we add a new form field on the form. I would like something like when i select op1, then it just show op1 options on second select.
<select id="id1" name="optionshere">
<option relone="op1">opt one</option>
<option relone="op2">opt two</option>
</select>
<select id="id2" name="resulthere">
<option relone="op1">ans 1 op1</option>
<option relone="op1">ans 2 op2</option>
<option relone="op2">ans 1 op2</option>
</select>
Any idea?
thanks all
Here's a method without jQuery:
When you select an option in the first selectbox, it will hide everything that doesn't match its relone.
var id1 = document.getElementById("id1");
var id2 = document.getElementById("id2");
id1.addEventListener("change", change);
function change() {
for (var i = 0; i < id2.options.length; i++)
id2.options[i].style.display = id2.options[i].getAttribute("relone") == id1.options[id1.selectedIndex].getAttribute("relone") ? "block" : "none";
id2.value = "";
}
change();
<select id="id1" name="optionshere">
<option relone="op1">opt one</option>
<option relone="op2">opt two</option>
</select>
<select id="id2" name="resulthere">
<option relone="op1">ans 1 op1</option>
<option relone="op1">ans 2 op1</option>
<option relone="op2">ans 1 op2</option>
</select>
If Jquery is an option you may go with something like this:
<script type='text/javascript'>
$(function() {
$('#id1').change(function() {
var x = $(this).val();
$('option[relone!=x]').each(function() {
$(this).hide();
});
$('option[relone=x]').each(function() {
$(this).show();
});
});
});
</script>
Then to expand:
There really are many ways in which you can solve this predicament, depending on how variable your pool of answers is going to be.
If you're only interested in using vanilla javascript then let's start with the basics. You're going to want to look into the "onchange" event for your html, so as such:
<select onchange="myFunction()">
Coming right out of the w3schools website, on the Html onchange event attribute:
The onchange attribute fires the moment when the value of the element
is changed.
This will allow you to make a decision based on this element's value. Then inside your js may branch out from here:
You may use Ajax and pass to it that value as a get variable to obtain those options from a separate file.
You may get all options from the second div through a combination of .getElementbyId("id2") and .getElementsByTagName("option") then check for their individual "relone" attribute inside an each loop, and hide those that don't match, and show those that do.
Really, it's all up to what you want to do from there, but I personally would just go for the Jquery approach

Get the values of all select options on change event 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!

Javascript to hide select box elements not working in IE

Hey, not sure if I'm going about this the right way. I have two different select boxed. What needs to happen is when a certain item in box 1 is selected, certain items in box 2 are hidden. What I have works fine in FF but not in IE....thoughts?
<div>
<label class="form_label">Apparel</label>
<select id="Choices" size="1" style="clear: right;" onchange"changeThis();">
<option value="select">Pick Your Product</option>
<option value="1">choice 1</option>
<option value="2">choice 2/option>
<option value="3">choice 3</option>
</select>
</div>
<div>
<label class="form_label">Size</label>
<select id="Sizes" size="1" style="clear: right;">
<option value="select">Choose Your Size</option>
<option value="SC">Small Child</option>
<option value="IC">Intermediate Child</option>
<option value="MC">Medium Child</option>
</select>
</div>
...
function changeThing(choice)
{
var item = document.getElementById("Choices");
var size = document.getElementById("Sizes");
var selitem = item.options[item.selectedIndex].value;
if(selitem == '2546')
{
for(i=0; i<2; i++)
{
size[i].style.display = 'none';
//alert(size[i]);
}
}
Try using this instead:
http://www.w3schools.com/CSS/pr_class_visibility.asp
It would come out as:
size[i].style.visibility='hidden';
EDIT
Oh, welcome to StackOverflow!
I had the same problem some days ago. IE does not allow the using of visible:hidden or display:none for option element.
You can solve this problem storing the options of select1 in a variable. This variable will have all possible values, so when the value of select1 was changed you can remove all values of select2 and then get the options you need from variable to put into select2.
To summarize:
Store all possible values in a variable
When select1 was changed remove all options of select2
Filter the options(get these values from varible of step1) you need and put into select2
You cannot display:none remove will completely remove it, if you want the user not to choose it use disabled. you could do something like this
function changeThing()
{
var item = document.getElementById("Choices");
var size = document.getElementById("Sizes");
var selitem = item.options[item.selectedIndex].value;
if(selitem == '3')
{
for(i=1; i<2; i++) // filter logic here
{
size[i].disabled = true; //false - to reset
//alert(size[i]);
}
}
size.selectedIndex = 0; // reset the selection so a disabled item may not be selected. }
It depends on how you are firing off the event that calls the changeThing() function. Not sure about IE9, but IE8 and on back has issues with the onChange event. It basically avoids it in IE. You'll have to use onClick instead.
If you are using jQuery to fire the event, the onchange event should work correctly in all browser (even IE). Not sure how other Javascript libraries do it.
You need to remove this options completely to make it work in IE.
size.remove(i);
So you need to store your options in array and load it back when needed.

Categories

Resources