How should i get previous selected option automatically in dropdown in javascript - javascript

In javascript, in a dropdown menu if we select one option and in that dropdown how can I get a dropdown option which had selected previous option automatically on current option (if that current option fails on certain condition).

As you've already discovered, there is no way to get the previously selected value when the dropdown is changed directly from the dropdown itself.
The best option is to store the currently selected value, my preference is via a data- attribute.
So if for example you have a select like the following...
<select>
<option value="1" selected>One</option>
<option value="2">Two</option>
</select>
You would include the currently selected value as a data-previousvalue attribute... this would be part of the code that creates the control in the first place...
<select data-previousvalue="1">
<option value="1" selected>One</option>
<option value="2">Two</option>
</select>
Then when you change the select, you can check at the current value and if necessary reset it back to that stored one.
In the following example, if you select the third item Three (bad) it will automatically take you back to the previously selected option...
window.addEventListener("load", function() {
// Get the dropdown
var dd = document.getElementsByTagName("select")[0];
// When the dropdown changes
dd.addEventListener("change", function(){
// If it's a bad one
if (dd.value == "3") {
// Reselect the previous value
dd.value = dd.getAttribute("data-previousvalue");
}
// Now store the value for the next time
dd.setAttribute("data-previousvalue", dd.value);
});
});
<select data-previousvalue="4">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three (bad)</option>
<option value="4" selected>Four</option>
</select>
And if you have jquery available...
$(function(){
$("select").on("change", function(){
var $dd = $(this);
// If it's a bad one
if ($dd.val() == "3") {
// Reselect the previous value
$dd.val($dd.data("previousvalue"));
}
// Now store the value for the next time
$dd.data("previousvalue", $dd.val());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select data-previousvalue="4">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three (bad)</option>
<option value="4" selected>Four</option>
</select>
If you can't add the data attribute to the control at the point of render, then you can also set it on the page load...
window.addEventListener("load", function() {
// Get the dropdown
var dd = document.getElementsByTagName("select")[0];
// Set the currently selected value into the attribute
dd.setAttribute("data-previousvalue", dd.value);
// When the dropdown changes
dd.addEventListener("change", function(){
// If it's a bad one
if (dd.value == "3") {
// Reselect the previous value
dd.value = dd.getAttribute("data-previousvalue");
}
// Now store the value for the next time
dd.setAttribute("data-previousvalue", dd.value);
});
});
<select>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three (bad)</option>
<option value="4" selected>Four</option>
</select>
If you have jquery available to you...
$(function(){
$("select")
.each(function(i,v) {
var $dd = $(this);
$dd.data("previousvalue", $dd.val());
})
.on("change", function(){
var $dd = $(this);
// If it's a bad one
if ($dd.val() == "3") {
// Reselect the previous value
$dd.val($dd.data("previousvalue"));
}
// Now store the value for the next time
$dd.data("previousvalue", $dd.val());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three (bad)</option>
<option value="4" selected>Four</option>
</select>

You can do it setting element.val(previousStatus)
// Your changing value should assign on adStatus
// May be its come from database(previous status) or depends on user activity
let adStatus = 'Unfriendly';
$('#AdblockType').val(`${adStatus}`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="AdblockType">
<option value="Friendly">Friendly</option>
<option vlaue="Unfriendly">Unfriendly</option>
</select>

Related

Add new select with unqiue name onchange of previous select

I have a job that requires several hundred select elements on a page. I want to show each select dynamically as the previous is changed. I have a working version in which I put all the select elements in the markup, and then used a simple function to hide them all and show only the first. Then on change of each select the next is added.
This works just fine, but is obviously not ideal. I don't want to put 500 select items in the markup and hide them all for no reason, and my JS function would be 1500 lines long. Plus that would make me feel silly.
How can I automate this process with JS?
I do not need each select to have a unique id, but I do need each select to have a unique and incremented name. Is this possible? I have a working fiddle.
HTML:
<select name="select-one" class="hidden" id="one">
<option value="">not this one</option>
<option value="">pick this one</option>
</select>
<select name="select-two" class="hidden" id="two">
<option value="">not this one</option>
<option value="">pick this one</option>
</select>
<select name="select-three" class="hidden" id="three">
<option value="">not this one</option>
<option value="">pick this one</option>
</select>
<select name="select-four" class="hidden" id="four">
<option value="">not this one</option>
<option value="">pick this one</option>
</select>
JS:
$(document).ready(function() {
$('.hidden').hide();
$('#one').show();
$('#one').change(function(){
$('#two').show();
});
$('#two').change(function(){
$('#three').show();
});
$('#three').change(function(){
$('#four').show();
});
// and so forth...
});
HTML:
<select class="hidden" id="one" name='name_0'>
<option value="">not this one</option>
<option value="">pick this one</option>
</select>
jQuery
$('select').on('change', function() {
$('body').append($(this).clone(true))
})
Result:
Note we are using the overload of the clone() method. This means event handlers and data will be copied along with the elements. So whatever event handler you attached to the original select gets cloned.
If you want to increment the name just use a counter and add the attribute after the clone:
cnt=0;
$('select').on('change', function() {
cnt++
$('body').append($(this).clone(true).attr('name', 'name_' + cnt))
})
My solution:
CSS
.hidden {
display: none;
}
JS
const createSelect = index => `
<select name="select-${index}" class="hidden select" data-index=${index}>
<option value="">not this one</option>
<option value="">pick this one</option>
</select>
`;
$(document).ready(function() {
// Generate 100 selects
for (let i = 0; i < 100; i++) {
$("body").append(createSelect(i));
}
// Show first select
$(`.select[data-index='0']`).show();
$('.select').on('change', function() {
// Store index of a select currently changed
const index = parseInt($(this).attr('data-index'), 10);
// Show next select
$(`.select[data-index='${index + 1}']`).show();
});
});

I have two select boxes. I want to enable second select box only if i click a particular option in first select box [duplicate]

I have two dynamic dropdowns but both dropdown's value and options are same. What I want that if user select 'apple' from first dropdown then the second dropdown's apple option will be disabled (using javascript). In short user can not select same value from both.
//first drop down
<select name="fruit1">
<option value="1">Apple</option>
<option value="2">Mango</option>
</select>
//second dropdown
<select name="fruit2">
<option value="1">Apple</option>
<option value="2">Mango</option>
</select>
I have tried with jQuery:
function witness()
{
var op=document.getElementById("witness1").value;
$('option[value='+op+']').prop('disabled', true);
}
But with this both dropdown's value are disabled and if I select mango then apple will not enabled it remains disabled. I know I did not pass id so both dropdown value are disabled but where should i pass ?
If user select apple then in second dropdown apple will be disabled, I want to do this using Javascript or jQuery.
Fiddle: https://jsfiddle.net/3pfo1d1f/
To get the functionality you're after, you need to hook into the change event on the first dropdown, in order to disable the matching element in the second drop-down.
I also initialised the first element in the second dropdown as disabled ( as this chosen by default in the first dropdown)
Used jquery as you are:
HTML:
<!-- first dropdown -->
<select id="fruit1">
<option value="1">Apple</option>
<option value="2">Mango</option>
</select>
<br /> <br />
<!-- second dropdown -->
<select id="fruit2">
<option value="1" disabled>Apple</option>
<option value="2">Mango</option>
</select>
JQuery:
$('#fruit1').on( "change", function() {
var op = $( this ).val();
$('#fruit2 option').prop('disabled', false);
$('#fruit2 option[value='+op+']').prop('disabled', true);
});
This should still work, no matter how many options you have in both the dropdowns
Try this out:
HTML:
<select id='fruit1' onchange="witness();">
<option selected></option>
<option value="1">Apple</option>
<option value="2">Mango</option>
</select>
<select id='fruit2'>
<option selected></option>
<option value="1">Apple</option>
<option value="2">Mango</option>
</select>
JQuery:
function witness(){
$("#fruit2 option").each(function(){
if($("#fruit1 option:selected").val() == $(this).val())
$(this).attr("disabled", "disabled");
else
$(this).removeAttr("disabled");
});
}
You can see a working exemple here:
https://jsfiddle.net/mqjxL4n0/
<select name="firstselect" id="firstselect">
<option value="apple">Apple</option>
<option value="orange">Orange</option>
</select>
<select name="secondselect" id="secondselect">
<option value="apple">Apple</option>
<option value="orange">Orange</option>
</select>
<script>
$(document).ready(function(){
$('#firstselect').change(function(){
var firstselected = $(this).val();
if(firstselected ){
$('#secondselect option').each(function(){
$(this).prop('disabled', false);
if($(this).val()==firstselected )
$(this).prop('disabled', true);
});
}
else {
$('#secondselect option').each(function(){
$(this).prop('disabled', false);
});
}
});
});
</script>

jquery get current selected value from multiple

I have select drop down where I use array sign in name like
<select name="services[]" id="service_id" multiple>
<option value="4">four</option>
<option value="1">one</option>
<option value="3">three</option>
</select>
Now I need to get current (last) selected value from drop down on change event.
What I have tried so far is
var clicked = $('#service_id option:selected').last().val();
alert(clicked);
//also tried as
//$(this).closest('select').find('option').filter(':selected:last').val();
//and this is tried too
// $(this).val();
// this.value;
All these giving me wrong value when multi select.
What I need
If select four then next select one it should alert 1 (remember when multi selection).
If select three and then next select four then it should alert 4
In brief ALWAYS need Clicked option's value even in multi select
** Not possible to remove array sign from name services[]
There is no native way, but you could save the order of the options clicked, then get the last.
ie, against a data attribute on the select:-
$('#service_id option').click(function() {
var values = $(this).parent().data('values') || [];
var index = values.indexOf(this.value);
index >= 0 ? values.splice(index, 1) : values.push(this.value);
$(this).parent().data('values', values);
});
$('#service_id').click(function() {
var values = $(this).data('values');
console.log(values);
var last = values[values.length - 1];
console.log('last:' + last);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="services[]" id="service_id" multiple>
<option value="4">four</option>
<option value="1">one</option>
<option value="3">three</option>
</select>
Try this demo
$(function(){
var last_selected;
$("#service_id option").click(function(){
if($(this).is(":selected")) {
last_selected = $(this).attr('value');
}
$("#result").html(last_selected);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="services[]" id="service_id" multiple>
<option value="4">four</option>
<option value="1">one</option>
<option value="3">three</option>
</select>
<p>Last selected : <span id="result"></span></p>
So you just want to get the last selected element?
Just create a variable to store the last selected element in each option click as shown by this demo:
var currLast = null;
$('#service_id').children().on('click', function(){
var val = $(this).val();
if (currLast === val) { // do nothing if current selected is the same elem
return;
}
currLast = val;
console.log(currLast)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="services[]" id="service_id" multiple>
<option value="4">four</option>
<option value="1">one</option>
<option value="3">three</option>
</select>

focusing on an element after an event is fired

I want to display an alert message if the user does not select any item in the dropdown then focus that dropdown. I want to do this in all dropdowns with the class "select".
$("#submit").click(function(event) {
if (!$(".select").val()) {
alert("please select one");
event.preventDefault();
$(".select").focus();
}
});
Now, this works fine for one dropdown, but when there are multiple dropdowns, it focuses on the very last, not the particular dropdown.For example, consider an html page with three dropdowns.
<select class="select" id="usertype">
<option value="">Select one</option>
<option value="guest">Guest</option>
<option value="admin">Admin</option>
</select>
<select class="select" id="gender">
<option value="">Select one</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<select class="select" id="languages">
<option value="">Select one</option>
<option value="c++">c++</option>
<option value="c">c</option>
</select>
If I selected some items in both languages and gender but select nothing from usertype ("Select one"'s value is ""), the alert message is displayed, but the focus goes to languages, instead of usertype.
What should I do to focus on the unselect dropdown (or the first unselected if the user did not choose items from many dropdowns)?
How about this:
$("#submit").click(function(event) {
if (!$(".select").val()) {
alert("please select one");
event.preventDefault();
$(".select[selectedIndex=0]").focus();
}
});
You can do it with $.each,
$("#submit").click(function(event) {
$(".select").each(function(){
if (!$(this).val()) {
alert("please select one");
event.preventDefault();
$(this).focus();
return false;
}
});
});
Given the updated HTML, and in the face of some rampant unexplained down-voting, I'd suggest the following:
// binding the anonymous function of the 'click'
// method as the event-handler for clicks on the
// element with the id of 'submit':
$("#submit").click(function (event) {
// caching all the elements with the class of
// 'select':
var selects = $('.select'),
// filtering those cached elements elements,
// retaining only those for whom the assessment
// provided to filter()'s anonymous function
// returns a value of true, or is 'truthy':
hasNoValue = selects.filter(function () {
// here we're checking that the current
// select has a value of '' (empty string):
return this.value === '' &&
// and that its currently selected <option>
// (this.options is a collection of the
// <option> elements within the current
// <select> element, and this.selectedIndex
// is the index of the selected <option>
// in the options collection) has the
// text of 'Select one'
// (String.prototype.trim() removes leading
// and trailing white-space from a supplied
// string):
this.options[this.selectedIndex].text.trim() === 'Select one'
});
// if the hasNoValue collection of <select> elements has a length
// other than (the 'falsey') 0, then we enter the 'if':
if (hasNoValue.length) {
// preventing the default action of the click event:
event.preventDefault();
// selecting the first element from the collection
// held within hasNoValue, and focusing that one:
hasNoValue.eq(0).focus();
}
});
$("#submit").click(function(event) {
var selects = $('.select'),
hasNoValue = selects.filter(function() {
return this.value === '' && this.options[this.selectedIndex].text.trim() === 'Select one'
});
if (hasNoValue.length) {
hasNoValue.eq(0).focus();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="select" id="usertype">
<option value="">Select one</option>
<option value="guest">Guest</option>
<option value="admin">Admin</option>
</select>
<select class="select" id="gender">
<option value="">Select one</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<select class="select" id="languages">
<option value="">Select one</option>
<option value="c++">c++</option>
<option value="c">c</option>
</select>
<button id="submit">submit button</button>
External JS Fiddle demo, for experimentation and development.
References:
JavaScript:
HTMLOptionElement.
HTMLSelectElement.
String.prototype.trim().
jQuery:
click().
eq().
filter().
focus().

Disable Drop Down Options Once Chosen In Other Dropdown

I have 12 drop downs input areas, 1 for each of the months of the year. Each drop down has the choice of the same 24 options.
I need to make it so that, for example, if in the January drop down box you chose option #4, that option #4 cannot be selected in any of the other drop down menus. It would still be in the drop down, but would just be disabled.
This would have an ajax trigger to check the value against the other drop downs and dynamically change the other drop down menus.
Is there a loop I can do to check and disable these values dynamically without having to make a lot of if statements?
You can use jQuery to find the option element in all other dropdowns (in my example, designated by a certain class...and can easily be changed to another selector - I thought the selector "select" was too broad), and then disable the actual option element by using .prop("disabled", true). But it's a little more tricky than this, as you need to keep track of the previous selected value to enable the dropdown again when a different value is chosen. Here's an example that will hopefully help:
http://jsfiddle.net/p5Arj/
$(document).ready(function () {
$(".test").each(function () {
var $self = $(this);
$self.data("previous_value", $self.val());
});
$(".test").on("change", function () {
var $self = $(this);
var prev_value = $self.data("previous_value");
var cur_value = $self.val();
$(".test").not($self).find("option").filter(function () {
return $(this).val() == prev_value;
}).prop("disabled", false);
if (cur_value != "") {
$(".test").not($self).find("option").filter(function () {
return $(this).val() == cur_value;
}).prop("disabled", true);
$self.data("previous_value", cur_value);
}
});
});
So this disables all other dropdowns' same options when you choose one, and makes sure that when you choose another, the previous one is enabled in all other dropdowns. For example, choose "3" in the first dropdown...look at the second dropdown - see that "3" is disabled...go back to the first dropdown and choose "1"...look at the second dropdown - see that "3" is enabled again but "1" is disabled. That's what the use of .data is for in my code.
Of course, you can replace the use of value with selectedIndex if you are 100% sure that all of the options will be the same for each select in question.
http://jsfiddle.net/Rk5e9/9/
Only about 10 lines, and no ajax!
<select class="unique-value">
<option value="-1" selected="selected">Default</option>
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
<select class="unique-value">
<option value="-1" selected="selected">Default</option>
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
<select class="unique-value">
<option value="-1" selected="selected">Default</option>
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
Script:
$(document).ready(function(){
$('.unique-value').focus(function(){
var val = $(this).val();
$(this).attr('data-current-value', val);
});
$('.unique-value').change(function(){
var val = $(this).val();
if(val != -1)
$('.unique-value option[value=' + val + ']').attr('disabled', 'disabled');
var oldval = $(this).attr('data-current-value');
$('.unique-value option[value=' + oldval + ']').removeAttr('disabled');
});
});​
I think this would be the shortest solution:
<select class="select-value">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
<select class="select-value">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
<select class="select-value">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
and the jquery code:
$(document).on('change', '.select-attendee', function(){
$current=$(this);
$(".select-attendee").not($current).children("option[value='"+$current.val()+"']").attr('disabled', "disabled");
});
Assuming you had a dropdown for each month, and an option for each week.
<select class="month" id="october">
<option class="week" value="week1">Week One</option>
<option class="week" value="week2">Week Two</option>
</select>
Lets say you select a week, and you listen for the event.
$(".month").change(function(event) {
// Get the week just selected.
var selectedWeek = $(this).children(".week:selected").val();
// Enabled all weeks before disabling the selected week.
$("option.week").removeAttr("disabled");
// Disable all week options matching this selection.
$("option.week[value="+selectedWeek+"]").attr("disabled", "disabled");
});

Categories

Resources