Dropdown menu item reversal - javascript

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;
}
});
});

Related

How to check if select element changed after close? [duplicate]

I would like to make a jQuery check if a select field was changed. If it changes, set an alert message (has changed), if returned to default, set another alert message (default value).
$('select').on('change',function () {
var isDirty = false;
$('select').each(function () {
var $e = $(this);
if (!$e[0].options[$e[0].selectedIndex].defaultSelected) {
isDirty = true;
}
});
if(isDirty == true) {
alert("has changed");
} else {
alert("default value");
}
});
Please advise if this is the proper way.
You don't need inner each loop. Plus $(this)[0] can be optimised to just this:
$('select').on('change', function () {
var isDirty = !this.options[this.selectedIndex].defaultSelected;
if (isDirty) {
alert("has changed");
} else {
alert("default value");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="" id="">
<option value="1">Label 1</option>
<option value="2" selected>Label 2</option>
<option value="3">Label 3</option>
<option value="4">Label 4</option>
</select>
I would do something like:
HTML:
<select data-default="one" id="the-select">
<option>one</option>
<option>two</option>
</select>
Javascript:
$('#the-select').change(function() {
var changed = $(this).val() != $(this).data('default');
alert(changed ? 'changed' : 'not changed');
});

Disable dropdown using 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.

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

Trigger the event when selected the same value in dropdown?

Issue: I have a dropdown with a list of years in it with nothing selected, the user selects "1976", I run a function. If the user clicks on the dropdown again and selects "1976" AGAIN, I want to run the function again.
$('select').on('change', function (e)
{
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
alert(valueSelected);
});
Simple JS
---------
<html>
<head>
<script>
var prevIndex = "";
function onSelect()
{
var currIndex = document.getElementById("ddList").selectedIndex;
if( currIndex > 0 )
{
if( prevIndex != currIndex )
{
alert("Selected Index = " + currIndex);
prevIndex = currIndex;
}
else
{
prevIndex = "";
}
}
}
</script>
</head>
<body>
<select id="ddList" onClick="onSelect()">
<option value="0">Select Me</option>
<option value="1">List1</option>
<option value="2">List2</option>
<option value="3">List3</option>
</select>
</body>
</html>
This basic idea should work using jQuery using click event:
$('#yourselect').click(function() {
console.log("your function");
});
A simple if statement could prevent firing off the function when initially clicking the select element.
The closest functionality that you're seeking that I can think of is the following:
-HTML-
<select class="opt-evt">
<option value="" selected="selected"></option>
<option value="1976">1976</option>
</select>
-jQuery-
$(document).ready(function(){
$('.opt-evt').change(function(){
$(this).blur();
}).blur(function(){
console.log($(this).find('option:selected').val());
});
});
The caveat is that if the user selects '1976' again, the desired event only gets fired onBlur.
http://jsfiddle.net/4G9Jf/
mouseup event should do the trick:
$('select').mouseup(function(){
console.log("hue");
});
http://jsfiddle.net/5Fcgr/
note that this will be triggered twice when a new value is selected in the listbox. Once when opening the options, and once when selecting an option.
I have fixed as below,
<html>
<head>
<script>
function onSelect()
{
var dd = document.getElementById('ddList');
var txtTerms = document.getElementById('selValue');
var storeLstSlct = document.getElementById('checkIndx');
var slctdValue = '';
if(dd.selectedIndex == 0)
{
return false;
}else if(storeLstSlct.value == dd.options[dd.selectedIndex].value)
{
storeLstSlct.value = 'abcd';
return false;
}else
{
slctdValue = dd.options[dd.selectedIndex].value;
if(txtTerms.value != '')
txtTerms.value = txtTerms.value + ' , ' + slctdValue;
else
txtTerms.value = slctdValue;
storeLstSlct.value = slctdValue;
}
}
</script>
</head>
<body>
<select id='ddList' onclick='onSelect()'>
<option value='0'>Select Me</option>
<option value='One'>List1</option>
<option value='Two'>List2</option>
<option value='Three'>List3</option>
</select>
<input type='hidden' name='checkIndx' id='checkIndx' />
<input type='text' name='selValue' id='selValue' />
</body>
</html>

Categories

Resources