jquery get current selected value from multiple - javascript

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>

Related

How should i get previous selected option automatically in dropdown in 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>

How to target outside $(this) in jQuery

I'm trying to use $('.selector').on('change', function(){}) then inside of it, I added each. What I want is to target the current .selector, if the current item is already selected then make it empty so you can select other item; there are multiple <select class='selector'> elements in the DOM. Please see my code below.
$(document).ready(function(){
$('.selector').on('change', function(){
var currentSelect = $(this).val();
if(currentSelect == ''){
$('.selector').each(function(){
if(currentSelect == $(this).val()){
alert("Sorry, you cannot select that item again.");
$(this).val('');
}
});
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<select class="selector">
<option></option>
<option value="Apple">Apple</option>
<option value="Mango">Mango</option>
<option value="Banana">Banana</option>
<option value="Watermelon">Watermelon</option>
</select>
<br><br>
<select class="selector">
<option></option>
<option value="Apple">Apple</option>
<option value="Mango">Mango</option>
<option value="Banana">Banana</option>
<option value="Watermelon">Watermelon</option>
</select>
<br><br>
<select class="selector">
<option></option>
<option value="Apple">Apple</option>
<option value="Mango">Mango</option>
<option value="Banana">Banana</option>
<option value="Watermelon">Watermelon</option>
</select>
<br><br>
<select class="selector">
<option></option>
<option value="Apple">Apple</option>
<option value="Mango">Mango</option>
<option value="Banana">Banana</option>
<option value="Watermelon">Watermelon</option>
</select>
You need 2 loops at each change events here.
to get all selected values.
to hide all values already selected from the other <select> elements.
Simple as that.
$(document).ready(function(){
var selected = []; // Global scope array.
$('.selector').on('change', function(){
var currentSelect = $(this).val();
var selected = []; // Array reset
$('.selector').each(function(){
var val = $(this).val();
if(val!=""){
selected.push($(this).val()); // Array fill
}
});
console.log(selected);
$('.selector option').each(function(){
if($.inArray($(this).val(),selected)!=-1){ // If not in array: hide
$(this).hide();
}else{
$(this).show();
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<select class="selector">
<option></option>
<option value="Apple">Apple</option>
<option value="Mango">Mango</option>
<option value="Banana">Banana</option>
<option value="Watermelon">Watermelon</option>
</select>
<br><br>
<select class="selector">
<option></option>
<option value="Apple">Apple</option>
<option value="Mango">Mango</option>
<option value="Banana">Banana</option>
<option value="Watermelon">Watermelon</option>
</select>
<br><br>
<select class="selector">
<option></option>
<option value="Apple">Apple</option>
<option value="Mango">Mango</option>
<option value="Banana">Banana</option>
<option value="Watermelon">Watermelon</option>
</select>
<br><br>
<select class="selector">
<option></option>
<option value="Apple">Apple</option>
<option value="Mango">Mango</option>
<option value="Banana">Banana</option>
<option value="Watermelon">Watermelon</option>
</select>
If I understood your question correctly, this would be the answer. By using $(this), you are applying whatever change to all select elements on the page. You want to do it just for the one that was clicked. For that reason, you should be very careful with $(this) and use $(event.target) instead. Read more about the differences here:
Difference between $(this) and event.target?
$(document).ready(function(){
$('.selector').on('change', function(e){
var currentSelect = $(e.target).val(); // if you need to pass/submit the value somewhere later
$(e.target).attr('disabled', 'disabled');
});
});
Why not simply disable the target element? You can still see what was selected and the user cannot click it again.
This solution is a little bit messy, but it works
$(document).ready(function(){
$(".selector").on("change", function(){
var currentSelect = $(this).val();
$(this).siblings().on("change", function(event){
if(currentSelect == $(this).val()){
$(this).val('')
alert("Sorry, you cannot select that item again.");
}
});
});
});
There isn't really a reason to loop through .each here.
What you can do, is .on('change') create an array of all values of elements with the .selector class. Then once you have that array, check how many instances there are of the element that was just selected. If that number > 1, then that selection has already been made in a different .selector element.
Working Pen:
https://codepen.io/anon/pen/WLvzMM
$(document).ready(function(){
$('.selector').on('change', function(){
// Put the value of all elements with the class of `.selector` into an array
var all = $.map($('.selector'), function (el) { return el.value; });
// Get value of the change that was just made
var currentSelect = $(this).val();
// Get the number of occurences of the value that was just selected
var occurences = $.grep(all, function (elem) {
return elem === currentSelect;
}).length;
// If there is more than one occurence (the one that was just selected), then prevent the selection.
if(occurences > 1){
alert("Sorry, you cannot select that item again.");
$(this).val('');
}
});
});

Change value of select list with value of another select list jquery

How can I change the value of a select list with the value of another select list
<select class="main-filter" id="Test1" name="Test1"><option value="">Select Option</option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
Need to replace #ReplaceThisText# with value selected from above select box
<select id="selectfilter" name="selectfilter" class="form-control main-filter">
<option value="">Sort Products</option>
<option value="/?id=na&selectfilter=hl&Type=#ReplaceThisText#">Chnage Value</option>
</select>
I have tried code from this link Change the Text of a Option with jQuery
and jquery how to find and replace a selected option that has a certain value
but cannot seem to get it to work
My code is
$('#Test1').change(function () {
sessionStorage.setItem("Test1", $(this).val());
$('.main-filter :selected:contains("#ReplaceThisText#")').val($(this).val());
location.href = $(this).val();
});
:contains will look at the .text() value - but your #ReplaceThisText# is not in the .text() value - so you'll need to use .filter() to find it instead:
Adding some console.logs so you can see what's happening and updated the .val(newval) code to make the replacement.
$('#Test1').change(function() {
var newval = $(this).val();
console.log("before", $(".main-filter :contains('Change Value')").val())
var opt = $('.main-filter option').filter(function() {
return $(this).val().indexOf("#ReplaceThisText#") >= 0;
});
console.log("opt length", opt.length);
opt.each(function() {
$(this).val($(this).val().replace(/#ReplaceThisText#/gi, newval));
});
console.log("after", $(".main-filter :contains('Change Value')").val())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="main-filter" id="Test1" name="Test1">
<option value="">Select Option</option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
<select id="selectfilter" name="selectfilter" class="form-control main-filter">
<option value="">Sort Products</option>
<option value="/?id=na&selectfilter=hl&Type=#ReplaceThisText#">Change Value</option>
</select>

Jquery autoselect select options of the same class

I have three select options drop down menus with class 'film', but the values are linked so that I have to select all to get result. In my case the HTML code looks like this:
<select name="sc30" id="sc30" onchange="autoSelect()" class="film">
<option>Choose an option...</option>
<option>---</option>
<option>White</option>
<option>Black</option>
</select>
<select name="ij10" id="ij10" onchange="autoSelect()" class="film">
<option>Choose an option...</option>
<option>---</option>
<option>Red</option>
<option>Green</option>
<option>Gold</option>
</select>
<select name="sc100" id="sc100" onchange="autoSelect()" class="film">
<option>Choose an option...</option>
<option>---</option>
<option>Gold glossy</option>
<option>Silver glossy</option>
</select>
If I select White option from id="sc30" the other two select options must take a value "---". Or if I select option Gold glossy from id="sc100" the other options from this class 'film' must take this value ---
I think that I have to use jQuery each() method. But how to check if any select option is selected and make other select options from this class with "---" value without already selected option. The code below don't work properly.
function autoSelect() {
$('.dummy').each(function(index, value){
if($(this).val() != '---') {
$(".dummy").val($(".dummy option:eq(1)").val());
}
});
}
$(function() {
$('select.film').on('change', function() {
var cb = $(this);
if (2 === cb.prop('selectedIndex')) {
$('select.film').not(cb).prop('selectedIndex', 1);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="sc30" id="sc30" class="film">
<option>Choose an option...</option>
<option>---</option>
<option>White</option>
<option>Black</option>
</select>
<select name="ij10" id="ij10" class="film">
<option>Choose an option...</option>
<option>---</option>
<option>Red</option>
<option>Green</option>
<option>Gold</option>
</select>
<select name="sc100" id="sc100" class="film">
<option>Choose an option...</option>
<option>---</option>
<option>Gold glossy</option>
<option>Silver glossy</option>
</select>
Try this : remove onchange="autoSelect()" from all select boxes and bind change event as shown below and select second option for each select box except the current one for which change event fired -
$(function(){
$('.film').change(function(){
//iterate all other select box except current using `not(this)`
$('.film').not(this).each(function(){
// get selected option for the current select box
var $selected = $(this).find('option:selected');
// if index of selected option is greater than 1,
// it means option is selected.
if($selected.index()>1)
$(this).val($(this).find('option:eq(1)').val());
});
});
});
DEMO
I just remove these two rows code:
var $selected = $(this).find('option:selected');
if($selected.index()>1)
and already is ok!
$(function(){
$('.film').change(function(){
//iterate all other select box except current using `not(this)`
$('.film').not(this).each(function(){
$(this).val($(this).find('option:eq(1)').val());
});
});
});

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