How to get previuos item of Dropdown using jquery or javascript - javascript

I want to get the previously selected value of a dropdown control using jquery or javascript.
How can i get this?
I tried with prev() selector of jquery but failed
$(ddlStatus).find("option").prev(":selected").attr("text");
if ddlStatus has items like A,B,C,D,E When the page loads B is selected but when user changes the item {let's say) E then I want previously selected i.e B.

Whenever a selection is made, save the value. On a new selection, you will then have the old value saved until you overwrite it.
You cannot do this dorectly, as you are after historical information - prev is about the ordering not the timing.

You could do it like this (not optimized but works):
$(document).ready(function(){
$(ddl).data('lastSelected', $(ddl).val());
});
$(ddlstatus).change(function(){
var lastSelected = $(this).data('lastSelected');
$(this).data('prevLastSelected', lastSelected);
$(this).data('lastSelected', $(this).val());
});
Then, to know the previously selected anytime, you just do:
var previouslySelectedValue = $(ddl).data('prevLastSelected');
What's good about this code is that the state is saved in the element and you don't use global vars, so it can be applied to any number of select boxes
Hope this helps. Cheers

here is a example:
HTML:
<select id="myselect">
<option value="one" selected="selected">one</option>
<option value="two">two</option>
<option value="three">three</option>
</select>
JQUERY:
var prev = null; //global
var cur = $('#myselect').val();//global
var flag = true;// global
$('#myselect').change(function() {
if (flag) {
prev = cur;
cur = $(this).val();
flag = false;
} else {
prev = cur;
cur = $(this).val();
}
});

Related

Changing one select option changes many others (JavaScript, JQuery)

I have a lot of select drop downs on a jsp page with a long list of elements. All of these drop downs have the same list of elements. Say I have to get the choice in descending order of preference from the user. I made (many) selects in the following way:
<select id="sel1" class="myClass">
<script>
populate(document.getElementById('sel1'));
</script>
</select>
...
<script>
function populate(op1)
{
var myArray = ["Chinese", "Italian", "Indian", ...//a long list of elements
var sel = op1;
for(var i = 0; i < myArray.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = myArray[i];
opt.value = myArray[i];
sel.appendChild(opt);
}
}
</script>
I have to create javascript/JQuery code in such a way that if a user selects an option the first select, that option gets disabled/removed in the others, leaving room for changes later. Say, the user's preference order is: Chinese, Indian, Italian... then on selecting Chinese in the first drop down, it gets disabled/removed from the other drop downs. Then, on selecting Indian from the second, it gets disabled/removed from all the others (including the previous one).
Now, if the user decides his order of preference is actually Chinese, Italian, Indian, .. he should be able to change his choice in such a way that the code doesn't break down. Say, we can have a button for reset and it resets all the choices by calling this function:
function resetFunc()
{
var options = document.getElementsByClassName("myClass");
for (var i = 0, l = options.length; i < l; i++)
{
options[i].selectedIndex = "0";
}
}
Any idea how to accomplish this? I need the code to be browser independent (while googling, I read somewhere that IE doesn't support removal of elements from drop down).
EDIT: Here's what I basically want:
http://jsfiddle.net/RaBuQ/1/
However, there's a problem in this. If a user keeps changing his choices, this thing breaks down. I'm able to select multiple choices.
$('select').change(function(){
var v = $(this).val();
$('select option[value="'+$(this).data('old-val')+'"]').prop('disabled', false);
$(this).data('old-val',v);
if(v != "0"){
$('select option[value="'+v+'"]').not(this).prop('disabled',true);
}
});
Here's a fiddle.
If I selected 'Football', 'Golf', 'Tennis', I'd need to select 'No preference' in the third box before I could then select it in one of the other boxes. I think this is acceptable from a UX perspective.
Since you've tagged this jQuery my example below will utilize that:
function populate() {
var myArray = ["Chinese", "Italian", "Indian"];
$('.myClass').each(function() {
var dis = $(this);
dis.append($("<option>").attr("value", "").text("select"));
$.each(myArray, function(i, o) {
dis.append($("<option>").attr("value", o).text(o));
});
});
}
function init() {
$('.myClass').html('').prop('disabled', false);
populate();
}
$(document).on('change', '.myClass', function() {
$('.myClass option[value="' + $(this).val() + '"]:not(:checked)').remove();
$(this).prop('disabled', true);
});
$('#reset').click(init);
init();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="sel1" class="myClass"></select>
<select id="sel2" class="myClass"></select>
<select id="sel3" class="myClass"></select>
<input type="button" id="reset" value="Reset options" />
The following might not be the most efficient solution, but you should try it if there is nothing better: when you change a select, empty all other selects and then fill them with all the other options.
lets say you have 3 selects: sel1, sel2, sel3
in the onchange event, you could call a function "fill_other_sel(number)" where number is the number of the current selector.
This function should delete current options and then populate checking with the previous selectors so that you dont populate with a previously selected value.
function fill_other_sel(number){
var num_selectors = 3;
while (number <= num_selectors){
number++;
$('#sel'+number).options.length=1;
populate('sel'+number, already_selected_values_array);
}
}
also you might add a parameter to your populate function showing which values have already been selected to prevent them from appearing again

Selected value on a cloned item not working as expected

Fiddle is here, containing this code: http://jsfiddle.net/enp2T/6/
<select id="aList">
<option value="0">0</option>
<option value="100">100</option>
<option value="200">200</option>
<option value="300">300</option>
</select>
<div id="newListContainer"></div>
$(function() {
var value = 300;
var clonedList = $('#aList').clone();
var listHtml = clonedList
.removeAttr('id')
.val(value)
.wrap('<div/>')
.parent()
.html();
$('#newListContainer').html(listHtml);
//$('#newListContainer>select').val(value);
});
I thought that my selected value of 300 would be maintained, but listHtml just contains a clone of the original list. I'm in a situation where it would be painful to try to re-find the object and set its value after it gets drawn (passing it to another external libraries function defers rendering till later, no complete callback unless I modify that library directly which I'm trying to avoid).
So am I doing something horribly wrong? Missing a quirk?
Clarification: I need to pass the HTML as a string, as the library that is using it is expecting a string.
There's no reason to make a round-trip to markup for this, and I suspect that's the problem, as jQuery's val sets the selectedIndex of the select element, which doesn't get serialized.
Just use the cloned element:
var wrappedList = clonedList
.removeAttr('id')
.val(value)
.wrap('<div/>')
.parent();
// Note: Not doing `.html()` at the end
// html(...) would empty the container and then add the HTML, so
// we empty the container and then append the wrapped, cloned list
$('#newListContainer').empty().append(wrappedList);
Updated working fiddle
jQuery clones the list with whatever you have selected - the problem here is that you don't have anything selected, so you're cloning a dropdown without a selected value (see here).
For an updated version of that script, check this updated jsFiddle.
Code:
$(function() {
var value = 300;
var clonedList = $('#aList').clone();
clonedList.find('option[value="' + value + '"]').attr('selected', 'selected');
var listHtml = clonedList
.removeAttr('id')
.val(value)
.wrap('<div/>')
.parent()
.html();
$('#newListContainer').html(listHtml);
//$('#newListContainer>select').val(value);
});
See this link. You can't set value to the select, you must set selected attribute to item with value=300.
$(function() {
var value = 300;
var clonedList = $('#aList').clone();
clonedList.find('option[value="' + value + '"]').attr("selected", true);
var listHtml = clonedList
.removeAttr('id')
//.val(value)
.wrap('<div/>')
.parent()
.html();
$('#newListContainer').html(listHtml);
//$('#newListContainer>select').val(value);
});
I have a mistake. #T.J. Crowder is right. jQuery can set value of select by .val(value) function. link
$(function() {
var value = 300;
var clonedList = $('#aList').clone();
var holderCloned = clonedList.removeAttr('id').val(value).wrap('<div/>').parent();
$('#newListContainer').empty().append(holderCloned);
});

How to select an option via jquery

I have a select form that looks kind of like this:
<select multiple="multiple" id="id_color_id" name="color_id"">
<option value="1">Red</option>
<option value="2">Blue</option>
<option value="3">Brown</option>
</select>
What I want to do is select the item above via javascript. This is actually part of a hidden form, so all I'm trying to do is leverage the serialize part of the form. I'm thinking it will just be easier to hack that after the serialize then to add this as well, but I also want to deselect any options that have already been selected.
So two questions:
How to select an option via javascript. All I will know is "Red", "Blue" or "Brown". I also have a look up dictionary that can get me the values as well.
How to deselect all options previous to selecting one of the above.
This is related to: Selecting options in a select via JQuery
Native Javascript:
var textToFind = 'Red';
var dd = document.getElementById('id_color_id');
for (var i = 0; i < dd.options.length; i++) {
if (dd.options[i].text === textToFind) {
dd.selectedIndex = i;
break;
}
}
or with jQuery:
$('#id_color_id option:contains('Blue')').prop('selected',true);
with variable:
var blue = "Blue";
$('#id_color_id option:contains(' + blue + ')').prop('selected',true);
And to deselect all selected options:
Native Javascript:
var elements = document.getElementById("id_color_id").options;
for(var i = 0; i < elements.length; i++){
if(elements[i].selected)
elements[i].selected = false;
}
jQuery:
$("#id_color_id option:selected").removeAttr("selected");
To select an option by it's content (considering what you posted is what you have)
$("#id_color_id option:contains('Red')").prop('selected',true);
jsFiddle Demo
You can set the value on the select box using the .val() method. Running this will reset any previously selected values, so you don't need to do anything specific to accomplish that part. You can also use an array to select multiple values, which may be of interest, since you are using a multi select.
$("#id_color_id").val(['1','2']);

jQuery onChange prop a value to inputs

I have a <select> drop down that I'm inserting into my HTML via jQuery. I don't have control over the HTML but I do have control over the JavaScript.
I'm trying to prop a value to an <input> element when you select an option. Basically, I have a <select> element with <option id="1"> and <option id="2"> onChange of this <select> element;
If you select option#1 it should prop the value dummy1 to input[name="Check_Config_PaymentGateway_CreditCards_Login1"] and the value dummy2 to input[name="Check_Config_PaymentGateway_CreditCards_Password"]
If you select option#2 it should prop the value dummy3 to input[name="Check_Config_PaymentGateway_CreditCards_Login1"] and the value dummy4 to input[name="Check_Config_PaymentGateway_CreditCards_Password"]
I've been working on this jsFiddle.
I'm pretty new at JavaScript in general, let alone jQuery. This is way to sophisticated for my skill... If you can help me, I'd really appreciate it.
Here you go: http://jsfiddle.net/VW9N6/6/
This binds to the change event of the <select> element to detect when its value changes, and then updates the value of the <input> elements.
Try something like below,
Edit: Cached input text boxes.
DEMO
var dummyValues = [['dummy1', 'dummy2'], ['dummy3', 'dummy4']];
var $loginInput = $('input[name=Check_Config_PaymentGateway_CreditCards_Login1]');
var $pwdInput = $('input[name=Check_Config_PaymentGateway_CreditCards_Password]');
$('#paymentDD').change(function () {
var selectedVal = parseInt($(this).val(), 10) - 1;
$loginInput.val(dummyValues [selectedVal][0]);
$pwdInput.val(dummyValues [selectedVal][1]);
});
Updated dummyValues var as you add move options to the drop down.
I'm a fan of caching elements whenever possible, so that's what I do. I also saw that you were using the latest jQuery (1.7.2) in your jsFiddle, so why not use the recommended .on() method and then call an immediate .change() to populate on load?
You could try something like this:
var $span = $('span#print_pagename'),
$login = $('input[name="Check_Config_PaymentGateway_CreditCards_Login1"]'),
$password = $('input[name="Check_Config_PaymentGateway_CreditCards_Password"]'),
$select = $('<select><option id="1">1</option><option id="2">2</option></select>');
$span.after($select);
$select.on('change', function() {
var $this = $(this);
if ($this.val() === '1') {
$login.val('dummy1');
$password.val('dummy2');
} else if ($this.val() === '2') {
$login.val('dummy3');
$password.val('dummy4');
}
}).change();

How to get Dropdown selected value on client side onchange event?

I have written a code for dropdown selected index changed event at client side using onchange event and create one JavaScript function.
Now, I want to retrieve selected values in this function. How can I get this value?
$("#DropDownlist:selected").val();
This will give you selected text.
$("#mydropdownid option:selected").text();
This will give you selected value
$('#mydropdownid').val();
HTML :
<select id="mySelect" class="myClass">
<option value='1'>One</option>
</select>
jQuery :
Now for getting selected value you can use the one of the following:
ONE :
var selected_value = $("#mySelect").val();
TWO :
var selected_value = $(".myClass").val();
THREE :
var dropdown = $("#mySelect option:selected");
var selected_value = dropdown.val();
The simplest, inside the event handler:
$('#elementID').change(function(event) {
event.target.value;
};
event is the event object sent to the handler, target is the object in the DOM from which the event generated, and value it's the DOM element current value. In the case of a select box this will work perfectly to get your selected value.
As you have tagged jQuery, I assume that's what you are using.
Simply use jQuery val()
var v = $("#yourSelectID").val();
alert("The value is: " + v);
You should also be able to use plain javascript:
var e = document.getElementById("yourSelectID");
var v = e.options[e.selectedIndex].value;
alert("The value is: " + v);

Categories

Resources