Enable/Disable dropdown - Javascript - javascript

I have the following code where 2 drop downs are available on the UI. When I select value "1" of drop down 1, the drop down 2 should be disabled. When I select value "1", the dropdown 2 is disabled. But I am not able to re-enable the drop down 2 when the user select value "2" from drop down 1. I am not sure since I am calling the performValidation() method for onClick event of both the options in drop down 1.
Code:
<html>
<head></head>
<script = "text/javascript">
function performValidation()
{
if (document.mainForm.criteriaOne.value == "1")
{
document.mainForm.criteriaTwo.options.length = 0;
document.mainForm.criteriaTwo.disabled = true;
}
else
document.mainForm.criteriaTwo.disabled = false;
}
</script>
<body>
<form name="mainForm" action= "" method ="get">
Criteria One:<select id = "criteriaOne">
<option value = "1" onClick ="performValidation()"> Select One - One</option>
<option value = "2" onClick ="performValidation()"> Select one - Two</option>
</select>
Criteria Two:<select id = "criteriaTwo">
<option value = "1" onClick ="performValidation()"> Select Two - One</option>
</select>
</form>
</body>
</html>

You need to wire up a function to the onchange event on the select something like
document.getElementById("criteriaOne").onchange = function()
{ // do some work to check the selectedIndex and determine whether to re- enable the other drop down}

You don't necessarily need
document.mainForm.criteriaTwo.options.length = 0;

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

Refresh a select tag to default value

I have 2 select tag. I want to refresh the values in the 2nd select tag to default , when the user click on the first select tag. How do I achieve it in Javascript
You will need to use onchange event to perform this task. The idea is when the first select is changed, you set the default value (here I choose to set to the first item of the list, but you can do whatever you need to re-initialize its value).
function initialize() {
var select_car = document.getElementById("select_car");
var select_power = document.getElementById("select_power");
select_car.selectedIndex = 0;
select_power.selectedIndex = 0;
select_car.addEventListener("change", function() {
select_power.selectedIndex = 1;
});
}
<body onload="initialize()">
<select id="select_car">
<option disabled>-- Select a car --</option>
<option>Mazda MX5</option>
<option>Nissan Skyline GTR</option>
</select>
<select id="select_power">
<option disabled>-- Select a power --</option>
<option>150CV</option>
<option>255CV</option>
</select>
</body>

change available html select options

I am looking for a javascript solution to change the available html select options. I have a javascript function being triggered at the right point, but I can't figure out how to change the available options. For example, if option A is selected in htmlselect1, I want the options in htmlselect2 to be updated. Thanks.
What I have seems to almost be working, but it has empty selections in the select options as well. This is the javascript function.
function setDurationChoices(){
var selectedType= hikeTypeID.value;
if(selectedType=== "G"){
document.inputForm.duration.options = new Option("3", "5", true);
}
else if(selectedType=== "H"){
document.inputForm.duration.options = new Option("2", "3", "4", true);
}
else if(selectedType=== "B"){
document.inputForm.duration.options = new Option("5", "7", true);
}
}
Here is where it is triggered:
<select id="hikeTypeID" name="hikeType" onchange="setDurationChoices()">
<option value="G">G</option>
<option value="H">H/option>
<option value="B">B</option>
</select>
Here is the select that I want to dynamically change:
<select name="duration">
<option value="3">3</option>
<option value="5">5</option>
</select>
The optional parameters for Option are the following
new Option([text[, value[, defaultSelected[, selected]]]])
text (required) - value shown on page
value - the value
defaultSelected - [true/false] - this is equivilavnt of adding the
selected attribute to the element on the html tag. So if you reset a
form, the value would remain selected.
selected - [true/false] - selects the value when option is set to true
This creates just a single option element like
<option value="G">G</option>
To add a option to say hikeTypeId, the code can be like
document.getElementById('hikeTypeId').options.add(new Option("g","g",false,false));
to flush all previous and add new, it can be done using [add(element[,index])] and remove(index)
while(document.getElementById('hikeTypeId').options.length)
document.getElementById('hikeTypeId').options.remove(0);
document.getElementById('hikeTypeId').options.add(new Option("g","g",false,false), 0);
document.getElementById('hikeTypeId').options.add(new Option("h","h",false,false), 1);
document.getElementById('hikeTypeId').options.add(new Option("i","i",false,true), 2);
You can as well use document.createElement('option') and set the attributes accordingly, if this is confusing.
var option = document.createElement('option');
option.text = text;
option.value = value;
option.selected = true;

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.

Enabling and disabling fields

I have a form that has two drop down fields lets say A is one and B is another. I want the drop down box B to be disabled until one of the value in the drop down A is selected .
How should I write a Java script?
Use the onchange event of dropdown A to check it's value and change the disabled property of dropdown B:
document.getElementById("dropdown_A").onchange = function ()
{
if (this.selectedIndex == 2) // if the 3rd option is selected
document.getElementById("dropdown_B").disabled = true;
}
Note this code needs to run after the dropdown A element (or the entire document) has been parsed.
For your dropdown_b, make the disabled property = "disabled"
for your dropdown_a, make the onchange to a function that will change dropdown_b's disabled property.
<html>
<head>
window.onload = function()
{
dda = document.getElementById("dropdown_A");
ddb = document.getElementById("dropdown_b");
dda.onchange = function()
{
if(dda.options[dda.selectedIndex] != "")
ddb.disabled = "";
};
}
</head>
<body>
<select id="dropdown_A">
<option value="" selected="selected"></option>
<option value="asdf">asdf</option>
<option value="12345">12345</option>
</select>
<select id="dropdown_B">
..
</select>
</body>
</html>
Basically, until the user selects an actual option nothing will happen... so the blank option [""] won't deselect the other select.

Categories

Resources