Disable dropdown using javascript - javascript

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.

Related

Multiple select dropdown menu without using CTRL button

Hy everyone, I want to select multiple dropdown menu , In which value select without CTRL. I tried this code http://jsfiddle.net/xQqbR/1022/ ,
Its working perfectly but I want to use the Shift key to select multiple values as well. In this code its not working.
I tried this code for selecting maximum value but still not working when we start selecting bottom to top.
var shifted1 = false;
var last_selected = '';
$('#abc option').mousedown(function(e) {
e.preventDefault();
var originalScrollTop = $(this).parent().scrollTop();
//console.log(originalScrollTop);
if (shifted1 == false) {
last_selected = $(this);
$(this).prop('selected', $(this).prop('selected') ? false : true);
}
//when shift key is pressed
else {
shifted1 = false;
for (var i = 0; i < $(this).parent().children().length; i++) {
if (last_selected.next().val() != $(this).val()) {
last_selected.next().prop('selected', true);
last_selected = last_selected.next();
} else {
last_selected = $(this);
$(this).prop('selected', true);
break;
}
}
}
var self = this;
$(this).parent().focus();
setTimeout(function() {
$(self).parent().scrollTop(originalScrollTop);
}, 0);
//return false;
});
$(document).on('keyup keydown', function(e) {
shifted1 = e.shiftKey;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<select id="abc" multiple="multiple">
<option value="1">Opt</option>
<option value="2">Opt</option>
<option value="3">Opt</option>
<option value="4">Opt</option>
<option value="5">Opt</option>
<option value="6">Opt</option>
<option value="7">Opt</option>
<option value="8">Opt</option>
<option value="9">Opt</option>
<option value="10">Opt</option>
<option value="11">Opt</option>
<option value="12">Opt</option>
<option value="13">Opt</option>
<option value="14">Opt</option>
<option value="15">Opt</option>
</select>
Thanks in advance.

How do I make 2 select boxes to dismiss each other if they mach and automatically select the second option to not match?

How do I make 2 select boxes to dismiss each other if they match, by automatically selecting the second option?
I want it instead of "alert" to have a function that automatically changes one option to the second option on one of the select option boxes when they match.
If I can keep the alert and have it automatically change that would be ideal, but I accept if the alert can not be kept.
JavaScript
<script src="http://code.jquery.com/jquery-1.8.1.min.js"></script>
<script type='text/javascript'>
$(window).load(function(){
$(function () {
'use strict';
$('.OBSMatch').on('change', function (event) {
var selectedValue = $(event.currentTarget).val();
var matchedDropdowns = $('.OBSMatch').filter(function (index) {
return $(this).val() === selectedValue;
});
if (matchedDropdowns.length > 1) {
alert("OBS! You cannot use it, because it matches each other!")
}
})
})
});
</script>
HTML
<select name="LangF1" class="OBSMatch">
<option value="zh-CN">Chinese (Simplified)</option>
<option selected value="en">English</option>
<option value="fr">French</option>
<option value="de">German</option>
<option value="ru">Russian</option>
<option value="es">Spanish</option>
<option value="" disabled>—</option>
<option value="auto">Auto Detect</option>
</select>
<select name="LangF2" class="OBSMatch">
<option value="zh-CN">Chinese (Simplified)</option>
<option value="en">English</option>
<option selected value="fr">French</option>
<option value="de">German</option>
<option value="ru">Russian</option>
<option value="es">Spanish</option>
<option value="" disabled>—</option>
<option value="auto">Auto Detect</option>
</select>
Update: I added this update from the complete code because the former good answer is not working correctly because of this button that does Switches the option languages.
<script language="JavaScript">
function getSelectedOption( elem ) {
return elem.options[elem.selectedIndex].value;
}
function setSelectedOption( elem, value ) {
for (let i = 0; i < elem.options.length; i++) {
elem.options[i].selected = value === elem.options[i].value;
}
}
function swapByOptionValue( selector1, selector2 ) {
var elem1 = document.querySelector(selector1),
elem2 = document.querySelector(selector2),
selectedOption1 = getSelectedOption( elem1 ),
selectedOption2 = getSelectedOption( elem2 );
setSelectedOption( elem1, selectedOption2 );
setSelectedOption( elem2, selectedOption1 );
}
function swapBySelectedIndex( selector1, selector2 ) {
var elem1 = document.querySelector(selector1),
elem2 = document.querySelector(selector2),
selectedOption1 = elem1.selectedIndex;
elem1.selectedIndex = elem2.selectedIndex;
elem2.selectedIndex = selectedOption1;
}
</script>
<input type="button" id="SwitchLang" onClick="swapByOptionValue('select[name=\'LangF1\']', 'select[name=\'LangF2\']');" value=" Swap ▲▼ Language ">
What you are asking for is an UI which allows the user to put the UI into an illegal state, gives an alert, and attempts to make things legal.
This really doesn't make for a great UI.
If at all possible, the user should be prevented from putting the UI into an illegal state, then there's no need for an alert and no need to correct anything. Such a strategy is eminently possible here.
The basic rules are fairly simple. On change of either select menu :
the other menu's counterpart to this menu's current selection should be disabled.
the other menu's other options should be enabled.
any initially disabled options need to be protected from becoming enabled.
var $menus = $('.OBSMatch').on('change', function(event) {
$menus.not(this).find('option').filter(function(index, opt) {
return opt.value === event.target.value;
}).prop('disabled', true) // disable the other menu's option corresponding to this menu's selection
.siblings().not('._protected').prop('disabled', false); // enable the other menu's options except any that are protected.
});
$menus.find('option').filter(function(index, opt) {
return opt.disabled;
}).addClass('_protected'); // protect any initially disabled options from being enabled
$menus.trigger('change'); // initialize everything
DEMO
"Auto Detect" may need to be handled as a special case - I'm not sure.
Alternatively, for a set of 3+ select menus ...
DEMO
Edit:
The two menu's selections can be switched as follows :
function switch_(selector) {
var $menus = $(selector);
var values = $menus.map(function() {
return this.value;
}).get().reverse(); // reverse() swaps the two values
$menus.each(function(i, menu) {
$(this).val(values[i]); // implement the switch
}).trigger('change'); // re-initialize everything
}
// call
switch_('.OBSMatch');
// so, assuming you have a #switch element :
$('#switch').on('click', function() {
switch_('.OBSMatch');
});
DEMO
The function can't be named switch, which is a javascript reserved word; therefore switch_
Are you looking for something like this?
The key here is, on change:
Get the value of target element
Get the value of the related select
If values match, change the value of target element to the next option
$(window).load(function() {
$(function() {
'use strict';
$('.OBSMatch').on('change', function(event) {
var selectedVal = $(event.currentTarget).val();
var relatedId = $(this).attr('data-related');
var $otherSelect = $('#' + relatedId);
var otherVal = $otherSelect.val();
if (selectedVal === otherVal) {
$(this).val($(this).find('option:selected').next().val());
// alert("OBS! You cannot use it, because it matches each other!");
}
})
})
});
// UPDATE: Added code from updated question to test solution along with rest of code:
function getSelectedOption( elem ) {
return elem.options[elem.selectedIndex].value;
}
function setSelectedOption( elem, value ) {
for (let i = 0; i < elem.options.length; i++) {
elem.options[i].selected = value === elem.options[i].value;
}
}
function swapByOptionValue( selector1, selector2 ) {
var elem1 = document.querySelector(selector1),
elem2 = document.querySelector(selector2),
selectedOption1 = getSelectedOption( elem1 ),
selectedOption2 = getSelectedOption( elem2 );
setSelectedOption( elem1, selectedOption2 );
setSelectedOption( elem2, selectedOption1 );
}
function swapBySelectedIndex( selector1, selector2 ) {
var elem1 = document.querySelector(selector1),
elem2 = document.querySelector(selector2),
selectedOption1 = elem1.selectedIndex;
elem1.selectedIndex = elem2.selectedIndex;
elem2.selectedIndex = selectedOption1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="LangF1" class="OBSMatch" data-related="ddl2" id="ddl1">
<option value="zh-CN">Chinese (Simplified)</option>
<option selected value="en">English</option>
<option value="fr">French</option>
<option value="de">German</option>
<option value="ru">Russian</option>
<option value="es">Spanish</option>
<option value="disabled" disabled>—</option>
<option value="auto">Auto Detect</option>
</select>
<select name="LangF2" class="OBSMatch" data-related="ddl1" id="ddl2">
<option value="zh-CN">Chinese (Simplified)</option>
<option value="en">English</option>
<option value="fr">French</option>
<option value="de">German</option>
<option value="ru">Russian</option>
<option value="es">Spanish</option>
<option selected value="disabled" disabled>—</option>
<option value="auto">Auto Detect</option>
</select>
<!-- UPDATE: Added code from updated question to test solution along with rest of code: -->
<input type="button" id="SwitchLang" onClick="swapByOptionValue('select[name=\'LangF1\']', 'select[name=\'LangF2\']');" value=" Swap ▲▼ Language ">

Change selected option value in dropdown

My dropdown looks like,
<select name="speed" id="ddlCustomer" class="form-control select-basic">
<optgroup label="CustomerId OrderDate SupplyDate Supplier">
<option value="1011_2">1011 2015-12-18 2015-12-22 ABC</option>
<option value="1011_2">1034 2015-12-23 2015-12-28 XYZ</option>
</optgroup>
</select>
Currently the dropdown shows options like "1011 2015-12-18 2015-12-22 ABC", that is fine but when user selects an option, I need to show only "CustomerId" i.e, 1011 in this case.
Your help is really appreciated. Thanks
Added script for focusout
customSelect.focusout(function () {
customSelectOptions.each(function (options) {
if ($(this).is(':selected')) {
$(this).text($(this).attr('value').split('_')[0]);
$(this).blur();
}
});
});
var states = [];
var customSelect = $('#ddlCustomer');
var customSelectOptions = customSelect.children().children();
// Get each state then push them to the array
// Initial state declaration
customSelectOptions.each(function() {
var state = $(this).text();
states.push({ state: state });
if ($(this).is(':selected')) {
$(this).text($(this).attr('value').split('_')[0]);
}
});
// On focus, always retain the full state name
customSelect.on('focus', function() {
customSelectOptions.each(function(index) {
$(this).text(states[index].state);
});
// On change, append the value to the selected option
$(this).on('change', function() {
customSelectOptions.each(function(options) {
if ($(this).is(':selected')) {
$(this).text($(this).attr('value').split('_')[0]);
}
});
// Un-focus select on finish
$(this).blur();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="speed" id="ddlCustomer" class="form-control select-basic">
<optgroup label="CustomerId OrderDate SupplyDate Supplier">
<option value="1011_2">1011 2015-12-18 2015-12-22 ABC</option>
<option value="1034_2">1034 2015-12-23 2015-12-28 XYZ</option>
</optgroup>
</select>
Try like this.You have use regex with text value of selected option.
var ddlCustomer = document.querySelector('#ddlCustomer');
ddlCustomer.addEventListener('change',function(){
text = $(this).find("option:selected").text();
var value = text.match(/[0-9]+/);
$(this).find("option:selected").text(value);
alert(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="speed" id="ddlCustomer" class="form-control select-basic">
<optgroup label="CustomerId OrderDate SupplyDate Supplier">
<option value="1011_2">1011 2015-12-18 2015-12-22 ABC</option>
<option value="1011_2">1034 2015-12-23 2015-12-28 XYZ</option>
</optgroup>
</select>
See fiddle here https://jsfiddle.net/88cozeaz/1/
document.getElementById('#ddlCustomer').onchange = function() {
var option = this.options[this.selectedIndex];
option.setAttribute('data-text', option.text);
option.text =$(this).val();
// Reset texts for all other but current
for (var i = this.options.length; i--; ) {
if (i == this.selectedIndex) continue;
var text = this.options[i].getAttribute('data-text');
if (text) this.options[i].text = text;
}
};

Dynamically create a function in JS

So I found this fiddle and I want to sort of merge it with this one. So when you click the button 3 times, they each have id 0, 1, 2 respectively. I then want to be able to hide the values of selected options from the other select elements. I tried to dynamically create the function from the working example but didn't manage to do it. Any help would be appreciated!
First fiddle;
JavaScript
$("#first").change(function() {
if($("#first").val() != "none") {
$("#second option[value!="+$("#first").val()+"]").show();
$("#second option[value="+$("#first").val()+"]").hide();
} else {
$("#second option[value!="+$("#first").val()+"]").show();
}
});
$("#second").change(function() {
if($("#second").val() != "none") {
$("#first option[value!="+$("#second").val()+"]").show();
$("#first option[value="+$("#second").val()+"]").hide();
} else {
$("#first option[value!="+$("#second").val()+"]").show();
}
});
HTML
<select id="first">
<option value="none">None</option>
<option value="one">Toyota</option>
<option value="two">Nissan</option>
<option value="three">Dodge</option>
</select>
<select id="second">
<option value="none">None</option>
<option value="one">Toyota</option>
<option value="two">Nissan</option>
<option value="three">Dodge</option>
</select>
Second fiddle;
JavaScript
arrSelects = [];
function generateSelect() {
var para = document.createElement("select");
$(para).attr('class', 'selectClass');
$(para).attr('id', arrSelects.length);
document.getElementById("createHere").appendChild(para);
arrSelects.push(' ');
fillSelect();
}
function fillSelect() {
$( ".selectClass").each( function () {
if ($(this).has('option').length < 1) {
for (var i = 0; i < 5; i++){
$(this).append('<option value='+i+'>'+i+'</option> ');
}
}
})
}
HTML
<button onclick="generateSelect()" onclick="generateFunction()">Click Me!</button>
<div id="createHere"></div>

Dropdown menu item reversal

I am new to javascript and my code looks as below
In HTML:
<select name="dropdown" onChange="javascript: alertUser()" >
<option value="0" selected>Eat</option>
<option value="1">Work</option>
<option value="2">Sleep</option>
<option value="3" >Enjoy</option>
In javascript:
function alertUser()
{
confirm("Are you sure?");
}
Now, here is my problem.
When I select an element from dropdown, it will pop up confirmation dialogue "Are you Sure?". If I click Ok, the selection should change to selected value. If I cancel, the selected value should reset back to previously selected value in dropdown list.
Could anyone please help me to solve the problem.
Thank you
You can use this:
window.onload = function () {
var select = document.getElementsByName('dropdown')[0];
var lastselected = select.value;
select.onchange = function () {
var newselected = select.value;
if (confirm("Are you sure?")) {
lastselected = newselected
return true;
}
select.value = lastselected;
}
};
I added onload to it so it will run when page loads. I removed your inline js, more clean. So your html would be:
<select name="dropdown">
<option value="0" selected>Eat</option>
<option value="1">Work</option>
<option value="2">Sleep</option>
<option value="3">Enjoy</option>
</select>
DEMO HERE
Here's an alternative using the 'selectedIndex' method.
http://jsfiddle.net/thetenfold/UjYg2/
html
<select name="dropdown">
<option value="0" selected>Eat</option>
<option value="1">Work</option>
<option value="2">Sleep</option>
<option value="3">Enjoy</option>
</select>
JavaScript
function addEvent(elem, type, func) {
if (elem.addEventListener) {
elem.addEventListener(type, func, false);
} else if (elem.attachEvent) {
elem.attachEvent('on' + type, func);
}
}
addEvent(window, 'load', function () {
var select = document.getElementsByName('dropdown')[0],
last = select.selectedIndex;
addEvent(select, 'change', function () {
if( confirm('Are you sure?') ) {
last = select.selectedIndex;
} else {
select.selectedIndex = last;
}
});
});

Categories

Resources