I'm having Two Dropdown name as Product and Product line and both are dependent on each other such that after selecting any product only Product Line dropdown will get enable. the sample structure is as below.
<select name="abb_sf_partners-product" data-abb-sf-productelement="" class="abb-select" disabled="">
<option value="">All products</option>
<option value="AA">Product1</option>
<option value="BB">Product2</option>
<option value="BB">Product3</option>
</select>
<select name="abb_sf_partners-product-line" data-abb-sf-productelement="" class="abb-select" disabled="">
<option value="">All products Line</option>
<option value="CC">ProductLine1</option>
<option value="DD">ProductLine2</option>
<option value="EE">ProductLine3</option>
</select>
<SCRIPT>
document.addEventListener("DOMContentLoaded", function() {
checkDropdownvalue();
});
function disableProductline() {
document.querySelector('select[name="abb_sf_partners-product-line"]').disabled = true;
}
function checkDropdownvalue() {
document.querySelector('select[name="abb_sf_partners-product"]').onchange = (e) => {
var selectedProductline = e.target.value;
alert(e.target.value)
if (selectedProductline == "AA") {
disableProductline();
}
}
}
</SCRIPT>
on select of AA in product dropdown ill needed to disable the ProductLine Dropdown.
But i'm guessing due to some razor view changes Product Line dropdown is keep getting enable as the data in Product Line is dynamically inserted
So is there any way such that my code will execute at the end to disable it.
You can try this approach.
document.addEventListener("DOMContentLoaded", function() {
checkDropdownvalue();
});
function checkDropdownvalue() {
const productSelect = document.querySelector('[name="abb_sf_partners-product"]');
const productLine = document.querySelector('[name="abb_sf_partners-product-line"]')
productSelect.addEventListener('change', function(e) {
if (e.target.value === 'AA') {
productLine.disabled = true;
} else {
productLine.disabled = false;
}
});
}
<select name="abb_sf_partners-product" data-abb-sf-productelement="" class="abb-select">
<option value="">All products</option>
<option value="AA">Product1</option>
<option value="BB">Product2</option>
<option value="BB">Product3</option>
</select>
<select name="abb_sf_partners-product-line" data-abb-sf-productelement="" class="abb-select" disabled="true">
<option value="">All products Line</option>
<option value="CC">ProductLine1</option>
<option value="DD">ProductLine2</option>
<option value="EE">ProductLine3</option>
</select>
As mentioned in My case Product Line dropdown was getting enable due to some razor view code. In order resolve this instead of comparing value of a product on change of product dropdown I have done the comparison on Product Line dropdown like if i hover my mouse over Product line dropdown it then trigger an event to check the selected product and compare it with the one i want (i have not used onClick as momentarily(for few milisec) it open the dropdown and then disable it ) i have used below JS script to achieve this.
document.addEventListener("DOMContentLoaded", function()
{
document.querySelector('select[name="abb_sf_partners-product-line"]').onmouseover = function fun() {
var selectedproduct = getSelectedProduct();
/* alert(selectedproduct.value); */
if(selectedproduct.value == "AA")
{
document.querySelector('select[name="abb_sf_partners-product-line"]').disabled = true;
}
else
{
document.querySelector('select[name="abb_sf_partners-product-line"]').disabled = false;
}
}
});
function getSelectedProduct(){
var sel = document.querySelector('select[name="abb_sf_partners-product"]');
var selectedP = getSelectedOption(sel);
function getSelectedOption(sel) {
var opt;
for ( var i = 0, len = sel.options.length; i < len; i++ ) {
opt = sel.options[i];
if ( opt.selected === true ) {
break;
}
}
return opt;
}
return selectedP
}
I hope it will help someone lol.
Look, i'm getting crazy, i can't get the selected item inside a normal select dropdown list (The values of the list are created dynamiclly with js).
I have a list of items and that are the columns of a table and i want when i click on an item, the column is added to the table and if i click another time in that item the column is removed.
I've tried to use a change event with jquery and onchange event with js but if i select the item two times in a row the column is added but not removed because the value hasn't changed.
I've tried to give a onclick event to the options of the select but nothing happens when i click on one. I've tried to capturo the clicked option from the select with jquery with this code:
$("#selectTableLt").on("click", "option", function() {
let clickedOption = $(this);
console.log(clickedOption);
});
But nothing happens.
Can anyone help me with this, please? Thank you
Edit:
My html:
<select name="leftColumns" id="selectTableLt"></select>
I load the options with javascript but they look like:
<option value="opt1">Option 1</option>
It's very simple
Check this out
<!DOCTYPE html>
<html>
<head>
<title>Select from dropdown list</title>
</head>
<body>
<h1>Select from dropdown list</h1>
<p id="result">Result here</p>
<select id="country">
<option value="None">-- Select --</option>
<option value="ID1">America</option>
<option value="ID2" selected>India </option>
<option value="ID3">England</option>
</select>
<script>
function GetSelectedValue(){
var e = document.getElementById("country");
var result = e.options[e.selectedIndex].value;
document.getElementById("result").innerHTML = result;
}
function GetSelectedText(){
var e = document.getElementById("country");
var result = e.options[e.selectedIndex].text;
document.getElementById("result").innerHTML = result;
}
</script>
<br/>
<br/>
<button type="button" onclick="GetSelectedValue()">Get Selected Value</button>
<button type="button" onclick="GetSelectedText()">Get Selected Text</button>
</body>
</html>
here is a solution to handle the multiple click events and fetch the dropdown selected value
var oldValue = null;
$(document).on("click","#selectTableLt", function(){
s = $(this);
val = s.val();
if (oldValue == null) {
oldValue = val;
} else {
var newValue = s.val();
if (newValue != "") {
var finalVal = oldValue == s.val() ? oldValue : newValue;
console.log(finalVal)
}
$(document).unbind('click.valueCheck');
oldValue = null;
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selectTableLt">
<option value="0">One</option>
<option value="1">Two</option>
</select>
You need to fetch the value using $.val() function
bind event to document in order to handle the dynamic event listener
$(document).on( eventName, selector, function(){} );
Using the Change Event:
$(document).on("change","#selectTableLt", function() {
let clickedOption = $(this).val();
console.log(clickedOption);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selectTableLt">
<option value="0">One</option>
<option value="1">Two</option>
</select>
Using the Click Event:
$(document).on("click","#selectTableLt", function() {
let clickedOption = $(this).val();
console.log(clickedOption);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selectTableLt">
<option value="0">One</option>
<option value="1">Two</option>
</select>
i want to create two drop down form and if i select an item on the first menu the second menu will display corresponding value. for example: if i select "fruit" on the first menu, then the second menu will display "apple", "banana" and so on. it must have values on them so i can insert it into database.
html is as follows:
<select id="firstmenu" name="fruit">
<option value="apple">apple</option>
<option value="banana">banana</option>
</select>
<br/>
<select id="secondmenu" name="vegetable">
<option value="carrot">carrot</option>
<option value="celery">celery</option>
</select>
javascript; i was thinking using something like this but i lack understanding of javascript
<script>
var a=document.forms["myform"]["fruit"].value;
var b=document.forms["myform"]["vegetable"].value;
if (a=="fruit")
{
...
}
</script>
could someone give me a code example? help is much appreciated, thanks.
Well,
how about using jQuery?
var items = [{
name: '---',
value: '',
subitems: []
},
{
name: 'Fruit',
value: 'fruit',
subitems: [{
name: 'Apple',
value: 'apple'
},
{
name: 'Banana',
value: 'banana'
}
]
},
{
name: 'Vegetable',
value: 'vegetable',
subitems: [{
name: 'Carrot',
value: 'carrot'
},
{
name: 'Celery',
value: 'celery'
}
]
}
];
$(function() {
var temp = {};
$.each(items, function() {
$("<option />")
.attr("value", this.value)
.html(this.name)
.appendTo("#firstmenu");
temp[this.value] = this.subitems;
});
$("#firstmenu").change(function() {
var value = $(this).val();
var menu = $("#secondmenu");
menu.empty();
$.each(temp[value], function() {
$("<option />")
.attr("value", this.value)
.html(this.name)
.appendTo(menu);
});
}).change();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="firstmenu" name="fruit"></select>
<br/>
<select id="secondmenu" name="vegetable"></select>
I used Javascript to create a dropdown menu. Then, if the user chose fruit in the main dropdown menu, I created "fruit" options, and if the user chose vegetables in the main dropdown menu, I created "vegetable" options.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function displayAccordingly() {
//Call mainMenu the main dropdown menu
var mainMenu = document.getElementById('mainMenu');
//Create the new dropdown menu
var whereToPut = document.getElementById('myDiv');
var newDropdown = document.createElement('select');
newDropdown.setAttribute('id',"newDropdownMenu");
whereToPut.appendChild(newDropdown);
if (mainMenu.value == "fruit") { //The person chose fruit
//Add an option called "Apple"
var optionApple=document.createElement("option");
optionApple.text="Apple";
newDropdown.add(optionApple,newDropdown.options[null]);
//Add an option called "Banana"
var optionBanana=document.createElement("option");
optionBanana.text="Banana";
newDropdown.add(optionBanana,newDropdown.options[null]);
} else if (mainMenu.value == "vegetable") { //The person chose vegetabes
//Add an option called "Spinach"
var optionSpinach=document.createElement("option");
optionSpinach.text="Spinach";
newDropdown.add(optionSpinach,newDropdown.options[null]);
//Add an option called "Zucchini"
var optionZucchini=document.createElement("option");
optionZucchini.text="Zucchini";
newDropdown.add(optionZucchini,newDropdown.options[null]);
}
}
</script>
</head>
<body>
<select id="mainMenu" onchange="displayAccordingly()">
<option value="">--</option>
<option value="fruit">Fruit</option>
<option value="vegetable">Vegetable</option>
</select>
<div id="myDiv"></div>
</body>
</html>
Every time the value of the dropdown menu changes, the function displayAccordingly() runs. It creates a new dropdown menu, and then, if the value of the main dropdown menu is fruit, it adds fruit options to the newly-created dropdown menu, and if the value of the main dropdown menu is vegetables, then it adds vegetable options to the newly-created dropdown menu.
I hope this helps! :)
EDIT: If you change the value of the dropdown twice, it creates 2 dropdown menus. I added another variable to fix that:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var created = 0;
function displayAccordingly() {
if (created == 1) {
removeDrop();
}
//Call mainMenu the main dropdown menu
var mainMenu = document.getElementById('mainMenu');
//Create the new dropdown menu
var whereToPut = document.getElementById('myDiv');
var newDropdown = document.createElement('select');
newDropdown.setAttribute('id',"newDropdownMenu");
whereToPut.appendChild(newDropdown);
if (mainMenu.value == "fruit") { //The person chose fruit
//Add an option called "Apple"
var optionApple=document.createElement("option");
optionApple.text="Apple";
newDropdown.add(optionApple,newDropdown.options[null]);
//Add an option called "Banana"
var optionBanana=document.createElement("option");
optionBanana.text="Banana";
newDropdown.add(optionBanana,newDropdown.options[null]);
} else if (mainMenu.value == "vegetable") { //The person chose vegetabes
//Add an option called "Spinach"
var optionSpinach=document.createElement("option");
optionSpinach.text="Spinach";
newDropdown.add(optionSpinach,newDropdown.options[null]);
//Add an option called "Zucchini"
var optionZucchini=document.createElement("option");
optionZucchini.text="Zucchini";
newDropdown.add(optionZucchini,newDropdown.options[null]);
}
created = 1
}
function removeDrop() {
var d = document.getElementById('myDiv');
var oldmenu = document.getElementById('newDropdownMenu');
d.removeChild(oldmenu);
}
</script>
</head>
<body>
<select id="mainMenu" onchange="displayAccordingly()">
<option value="">--</option>
<option value="fruit">Fruit</option>
<option value="vegetable">Vegetable</option>
</select>
<div id="myDiv"></div>
</body>
</html>
I guess this example may suits you requirement .Here I have set some static content for second option in dynamicdropdown() function.No problem you can make that with your dynamic content by Option object.For example
document.getElementById("subcategory").options[i] = new Option("key","value",false, false)
i will be you number of for dynamic values.
Please refer the demo part DEMO of dynamic drop down menu values
<html>
<head>
<title>Create dyanamic dropdown list in javascript</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript" type="text/javascript">
function dynamicdropdown(listindex)
{
document.getElementById("subcategory").length = 0;
switch (listindex)
{
case "fruits" :
document.getElementById("subcategory").options[0]=new Option("Please select fruits","");
document.getElementById("subcategory").options[1]=new Option("apple","apple");
document.getElementById("subcategory").options[2]=new Option("banana","banana");
document.getElementById("subcategory").options[3]=new Option("mangoes","mangoes");
break;
case "meats" :
document.getElementById("subcategory").options[0]=new Option("Please select meats","");
document.getElementById("subcategory").options[1]=new Option("pigs","pigs");
document.getElementById("subcategory").options[2]=new Option("chicken","chicken");
break;
}
return true;
}
</script>
</head>
<title>Dynamic Drop Down List</title>
<body>
<div class="category_div" id="category_div">Please specify food items:
<select name="category" class="required-entry" id="category" onchange="javascript: dynamicdropdown(this.options[this.selectedIndex].value);">
<option value="">Select food items</option>
<option value="Php">fruits</option>
<option value="Javascript">meats</option>
</select>
</div>
<div class="sub_category_div" id="sub_category_div">Please select foods:
<script type="text/javascript" language="JavaScript">
document.write('<select name="subcategory" id="subcategory"><option value="">Please select foods</option></select>')
</script>
<noscript>
<select name="subcategory" id="subcategory" >
<option value="">Please select foods</option>
</select>
</noscript>
</div>
</body>
</html>
Also refer for more details: Reference
i am a little confused about your problem, but i just wrote two sample examples for you DEMO1 and DEMO2
DEMO1 - javascript
window.onload = function() {
document.getElementById("firstmenu").addEventListener('change',function(e) {ha(e,'firstmenu','secondmenu');}, false);
};
function ha(e,first,second){
var firstOptions = document.getElementById(first).options;
var secondOptions = document.getElementById(second).options;
for(var i = 1, j = firstOptions.length; i < j; i++) {
secondOptions[i].value = firstOptions[i].value;
secondOptions[i].text = firstOptions[i].text;
}
};
DEMO2 - javascript
window.onload = function() {
document.getElementById("firstmenu").addEventListener('change',function(e) {ha(e,'secondmenu');}, false);
document.getElementById("secondmenu").addEventListener('change',function(e) {ha(e,'firstmenu');}, false);
};
function ha (e,id){
var index = e.target.selectedIndex;
document.getElementById(id).selectedIndex = index;
};
DEMO1 and DEMO2 have same HTML :
<select id="firstmenu" name="City">
<option value="--">--</option>
<option value="NY">NY</option>
<option value="LA">LA</option>
</select>
<br/>
<select id="secondmenu" name="zipCode">
<option value="--">--</option>
<option value="10001">10001(NY)</option>
<option value="90001">90001(LA)</option>
</select>
Hope this will help you !!
There are two selection buttons which need client-side validation. The user must select one of them, and if user chooses one, the other one will be disabled automatically.
This my script:
<html>
<head>
<script type="text/javascript">
function Check() //this the funciton for diasbled
{
var x =document.getElementById("supexp1");
var y =document.getElementById("supexp2");
if(x.value != "")
{
document.form1.supexp2.disabled=true;
}
else if(y.value != "")
{
{
document.form1.supexp1.disabled=true;
}
}
}
</script>
</head>
<body>
<form method="POST" action="destination.php" id="form1">
<select name="SUPEXP" id="supexp1" data-native-menu="false" onChange="Check()">
<option >Ekspedisi Local1</option> //this selection 1
<option >Ekspedisi Local2</option> //this selection 1
<option >Ekspedisi Local3</option> //this selection 1
</select>
<select name="SUPEXP" id="supexp2" data-native-menu="false" onChange="Check2()">
<option >Ekspedisi Expor2</option> //this selection 2
<option >Ekspedisi Expor2</option> //this selection 2
<option >Ekspedisi Expor2</option> //this selection 2
</select>
</form>
</body>
</html>
I use the jquerymobile framework and selection connect to the database. That code (JavaScript) is not running.
I hope this is what you trying to do based on your description here is a jsfiddle
$(document).ready(function() {
$('#supexp1').change(function() {
$('#supexp2').attr("disabled" , "disabled")
});
$('#supexp2').change(function() {
$('#supexp1').attr("disabled" , "disabled")
});
});
Try this code
if(x.value != ""){
document.getElementById("supexp2").disabled=true;
} else if(y.value != "") {
document.getElementById("supexp1").disabled=true;
}
I guess to get the value of the selected item you need to use some thing like this
var e = document.getElementById("supexp1");
var x = e.options[e.selectedIndex].value;
instead of
var x =document.getElementById("supexp1");
do the same for Y
I want to make the options of < select > show or hide by program(JS),is it possible?
It is just like the interesting tags in the front page of StackOverFlow, when you type in some words, the drop list will expand and give you suggestions.
ps.I know StackOverFlow didn't use select in this case, anyway just take it as an example.
You add or remove items from the options collection of the select.
Here is an example that removes one item and adds another:
<html>
<head>
<title></title>
<script type="text/javascript">
function init() {
// get a reference to the element
var sel = document.getElementById('sel');
// remove an option
sel.options[2] = null;
// create a new option and add to the select
var opt = document.createElement('option');
opt.value = '5';
opt.text = 'five';
sel.options.add(opt);
}
</script>
</head>
<body onload="init();">
<form>
<select id="sel">
<option value="0">zero</option>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</select>
</form>
</body>
</html>
function getCatListdef(sel)
{
var index = ajax.length;
ajax[index] = new sack();
ajax[index].requestFile = 'data.php?cat_code='+sel;
ajax[index].onCompletion = function(){ createCities(index) };
ajax[index].runAJAX();
}