I have a dropdown like below.
<select name="slt">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="3">Three +</option>
</select>
If I select the option Three + , after some page refresh the selected option became Three because Three and Three + has same value. How to avoid this and make the selected item as Three + after page refresh?
Thanks In Advance.
This is because the browser will automatically retain the value. If the value is a duplicate it will pick the first one it finds in the list.
To stop this behaviour, you need to give the Three+ option a unique value, for example:
<option value="3+">Three +</option>
If you cannot change the HTML at all, you will need to store the selected index of the element in localStorage, or a cookie, and set it again on load:
// set onchange
$('select').change(function() {
localStorage.setItem('sltIndex', $(this).prop("selectedIndex"));
});
// get onload
$(this).prop("selectedIndex", localStorage.getItem('sltIndex') || 0)
The pattern is the same for using a cookie, although the code would need amending.
Related
I am keeping the values of my option HTML tags selected using this code:
document.getElementById('select_itens_op').onchange = function() {
sessionStorage.setItem('pagina', document.getElementById('select_itens_op').value);
};
if (sessionStorage.getItem('pagina')) {
document.getElementById('select_itens_op').options[sessionStorage.getItem('pagina')].selected = true;
}
It was working just fine, but in one of my tags I came across with a problem. The option tags have numeric values and when I reload the page, what it's being kept is the option related to the index of the value stored in the sessionStorage.
Example:
<select name="select_itens_op" id="select_itens_op" ">
<option value="">Página</option>
<option value="2">2</option>
<option value="4">4</option>
<option value="8">8</option>
<option value="10">10</option>
</select>
If I select the option with value 2, this value will be stored into the sessionStorage, but when I refresh the page the option selected will be the one with value 4, since it is the position 2 of the list. If I select 4 the value stored will be 4 and the option returned would be 10, and so on.
If I use string values it works great, provided I add ids to these tags, but I need these numeric values. I already made my research and I didn't find a proper answer.
What is the best way to solve this?
Go for SelectElement.value directly:
const el_op = document.getElementById('select_itens_op');
// Set on init
if (sessionStorage.pagina) el_op.value = sessionStorage.pagina;
// Store on change
el_op.addEventListener('change', () => sessionStorage.pagina = el_op.value );
I have a <select> element in my html:
<select id="mySelect">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
I am using JSP/JSTL for the back end, and when the page loads I want to dynamically select one of these options based on a page attribute I get from the back end. In other words, in JavaScript/jQuery:
$(document).ready(function() {
$("#mySelect").find("option[val=${Var}]").prop("selected", true);
});
Ideally, when the page loads, the <select> element should show the option that is selected on screen (e.g if ${Var} is 4, it should display 4 by default, and allow the user to use the drop down to select any of the other options. This works fine in my browser and on Android devices, but when testing it on my iPhone 5S, the <select> displays the first option instead of the option that is selected when the page loads (the option with a value of ${Var}).
Any tips on how to ensure that it displays the correct selected value?
You can do it like this, when your page loads, it will execute this javascript:
var test = '<%= request.getAttribute("var") %>';
Here the var "test" will contain the attribute you set in your servlet called "var".
Then to make things easier, i am using jquery in this example, you can set your dropdown value to var. (but you must make sure that the dropdown select has a value with the variable var.) If var == 4 then it will set the dropdown select to value 4 on load.
$("#mySelect").val(test);
I've been using a nice, elegant plugin called DropKick for my webapp http://jamielottering.github.com/DropKick/, and I seem to be having a slight issue with it and am not sure how to go about trying to fix it. I am trying to programmatically change the value of the select drop down menu. Below is a description of my issue, and a link to JSFiddle.
HTML:
<select id="start" class="timePreference">
<option value="Choose">Choose</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
jQuery:
$('.timePreference').dropkick();
$('#someDiv').click(function() {
$('#start').val("1");
alert($('#start').val());
);
When I show the value in alert, it shows as one, however when I look at the labels on the option it stays at the default or whatever it was prior to the change.
For example, if my default was "Choose" and I click someDiv, then alert will show "1", so it changing, but the select dropdown will still show "Choose". Any suggestions. I may just be missing something small, not sure.
FSFiddle: http://jsfiddle.net/kdp8791/aNS9R/61/
working demo : With Commnet http://jsfiddle.net/aNS9R/218/ && without comments only 7 lines needed: http://jsfiddle.net/aNS9R/220/
-phew-
So, to start with I tried Change event [of dropkick] with in drop kick but its only for the change event within select and not from external element binding. i.e. in your case change button.
So; this is what I have done:
Explanation (if you interested)
I used firebug to inspect the variable and found that dropkick marshal your existing select with nice styling now when you used $('#timePreference option:selected').val("1"); dropkick actually did changed the selected value with in your element with id=timePreference but the div and ul and li styling which is created by dropkick is not changed yet.
For the chosen span it has a class .dk_label and for the current (green color) is given by .dk_option_current class.
Please Note I pretty much read the plugin and figure out what is happening from here: https://github.com/JamieLottering/DropKick/blob/master/jquery.dropkick-1.0.0.js
If you wish to use firebug and see how elements are se use this link : http://jsfiddle.net/aNS9R/218/show/ and play around with your inspect mode, you will see dropkick styling and how it works.
JQuery code
$(document).ready(function() {
$('#timePreference').dropkick();
$('#go').click(function(){
// Assign slected option value to your select here -
// you can also make it something like this but your existing cdoe works anyways $("select_id option[value='3']").attr('selected','selected');
$('#timePreference').val("1");
//Now assign the select text value to the dropkick added element.
//If you will use firebug you can see the nice <div>, <ul> & <li> structure which morph your dropdown.
$('.dk_label').text(1);
// further if you want green color to be selected. class=dk_option_current does that
// You need to loop through the dropkick hierachy
$(".dk_options_inner li").each(function(){
$(this).removeAttr('class');
if ($(this).text() == "1"){
$(this).attr('class', 'dk_option_current');
}
});
});
});
Hope this helps you mate, cheers!
HTML
<select id="timePreference">
<option value="Choose" selected="selected">Choose</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
<input name="go" id="go" type="button" value="change" />
You can set the dropkick value programmatically by jQuery trigger of a click event on the selected dropkick option.
$option = $('#dk_container_'+ k +' .dk_options a[data-dk-dropdown-value="'+ v +'"]');
$option.trigger("click");
Here k is the select id or name, and v is the selected value.
The click event of dropkick will automatically take care of setting the classes of options to reflect the change.
I'm a bit late answering this but I have recently come across the same issue - updating a Dropkick DDL after it has been created. I have taken Tats_innit's code and modified it slightly, creating a function that allows you to simply pass in the ID of the select element and the value you want to change it to.
function updateDropkickDDL(id, value) {
//Get the select element and dropkick container
var select = $(id);
var dk = select.prev('.dk_container');
//Set the value of the select
select.val(value);
//Loop through the dropkick options
dk.find('.dk_options_inner').children("li").each(function () {
var li = $(this);
var link = li.children('a');
//Remove the 'current' class if it has it
li.removeClass('dk_option_current');
//If the option has the value we passed in
if (link.data('dk-dropdown-value') == value) {
//Set the 'current' class on the option
li.addClass('dk_option_current');
//Set the text of the dropkick element
dk.find('.dk_label').text(link.text());
}
});
}
You should now be able to simply call updateDropkickDDL on the click of a button or similar, for example, to set the value of the dropdown in your question to 1 you would use:
$(document).ready(function(){
$('#start').dropkick();
$('#someDiv').click(function(){
updateDropkickDDL('#start', 1)
});
}
This function also allows the use of multiple dropkick dropdown lists on the page, only updating the specified dropdown.
I hope this will help someone else encountering this issue.
I know this question is a few months old, but for anyone looking this up later I wanted to add this link to a pull request on the DropKick repository that adds in a "reverse sync" option that updates the custom dropdown menu whenever the underlying select object changes. That allows you to just update the select object in your code and the DropKick custom dropdown updates on the "change" event.
https://github.com/JamieLottering/DropKick/pull/27
best way to change value
just add to jquery.dropkick-X.X.X.js
after
methods.reset = function () {
...
};
this code
// change value of current select
// usage: $("...").dropkick('select', select_value);
methods.select = function (value) {
for (var i = 0, l = lists.length; i < l; i++) {
var
listData = lists[i].data('dropkick'),
$dk = listData.$dk
;
if ($(this)[0] == $dk.next()[0]){
var $current = $($dk.find('li a[data-dk-dropdown-value="' + value + '"]')[0]).closest('li');
$dk.find('.dk_label').text(listData.label);
$dk.find('.dk_options_inner').animate({ scrollTop: 0 }, 0);
_setCurrent($current, $dk);
_updateFields($current, $dk, true);
var data = $dk.data('dropkick');
var $select = data.$select;
$select.val(value);
if ($.browser.msie)
$current.find('a').trigger('mousedown');
else
$current.find('a').trigger('click');
break;
}
}
};
usage: $("...").dropkick('select', select_value);
pros
- native change state of dropkick object
- change selected option in original select
- trigger event, useful if you listen "change" state
cons
- need to change original library
- long code :)
I have two drop-down lists populated from an array of same dates stored in a database. I want to use javascript or jquery to change the second drop-down list based on the selection from the first list. So an example would be if the user selects 03/03/2012 in the first, start date list, then I'd like the second list to only show or allow future dates within the array. 3/3, 3/2 and 3/1 would either be greyed out or removed and 3/4, 3/5 would remain as selectable options. Can anyone help with the javascript coding or make another recommendation?
<select id='start_date' name='data[sDate]' title='Use the drop list'>
<option value="" selected="selected"> </option>
<option value="03/05/2012">03/05/2012</option>
<option value="03/04/2012">03/04/2012</option>
<option value="03/03/2012">03/03/2012</option>
<option value="03/02/2012">03/02/2012</option>
<option value="03/01/2012">03/01/2012</option>
</select>
<select id='end_date' name='data[eDate]' title='Use the drop list'>
<option value="" selected="selected"> </option>
<option value="03/05/2012">03/05/2012</option>
<option value="03/04/2012">03/04/2012</option>
<option value="03/03/2012">03/03/2012</option>
<option value="03/02/2012">03/02/2012</option>
<option value="03/01/2012">03/01/2012</option>
</select>
With your actual example, if the two lists are exactly the same then it's pretty simple if you work with index(). Look http://jsfiddle.net/elclanrs/7YrqY/
$('#start_date').change(function(){
var $selected = $(this).find('option:selected');
$('#end_date')
.find('option')
.prop('disabled', false)
.eq($selected.index()-1)
.nextAll()
.prop('disabled', true);
});
Here's a few different solutions, including server side. This is a common scenario and I'm sure you could find more examples on this site if you searched a bit more.
http://css-tricks.com/dynamic-dropdowns/
using jQuery
$(function(){ //when the page is loaded
$("#start_date").change(function(){ //register a anonymous function that will be called when the element with id=start_date changes his values
var start = $(this).val(); //gets the value of the element
$("#end_date option").each(function(i){//for each option of end_date
if(new Date($(this).val()).getTime() < new Date(start).getTime()){ //if the date of the element is before the start
$(this).hide(); //hide the element
}else{
$(this).show(); //shows the element
}
});
});
});
Ive not tested but is something like that
I've googled and tried a number of ways to do this but none work for me so far. What I am looking for is quite simple: I want to be able to tell whether a dropdown has a selected value or not. The problem is that selectedIndex, :selected, val(), etc. do return results for the following case:
<select>
<option value="123">123</option>
<option value="234">234</option>
</select>
Obviously the browser will display this dropdown with the 123 option being selected but it will be selected only because there are no other options, in reality this dropdown doesn't have a selected value because there is no "selected" property. So basically I am trying to find how to tell apart the above dropdown from this one
<select>
<option selected value="123">123</option>
<option value="234">234</option>
</select>
var hasValue = ($('select > [selected]').length > 0);
Alternatively,
var hasValue = $('select').has('[selected]');
Quick solution:
<select>
<option selected></option>
<option value="123">123</option>
<option value="234">234</option>
</select>
Then see if you have a .val()
The approved answer doesn't seem to work for me.
Here is how I do it to check if all select options are selected:
if($('select option:selected').length > 0) {
/* Do your stuff here */
}
As far as I can tell, there is no functional distinction between your two examples. Essentially, the browser automatically selects the first option.
See, for example, the result of
$('option:selected')
on your first example.
If you really want to prevent this happening, you have two options. The first is to introduce a new, empty element into the select, per Jason's answer. The other option is to deselect the automatically selected value:
$(document).load(function(){
$('option:selected').attr('selected', false);
});
This clears the selection. Any result of $('select').val() that isn't an empty string will therefore be a change by the user.