JavaScript/HTML - Keeping numeric values from select dropdown list selected - javascript

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

Related

Un-/hiding options of a Select depending on value of another Select

Disclaimer: This seems to have been asked in similar form several times already but none of the solutions has worked for me. Additionally most of the solutions appear to be 4+ years old (up to 12+), who knows what changed in that time, I certainly don't.
The Problem: I want to hide all options in a select and only "unhide" them depending on what is chosen in another select.
I have two selects:
<select id="pool" name="pool" onchange="cause_mod()">
<option value="none" selected disabled hidden>Pool</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
and:
<select id="cause" name="cause">
<option value="none" selected hidden="true">cause/option>
<option value="sale" hidden="true">sale</option>
<option value="withdraw" id="withdraw" hidden>withdraw</option>
<option value="deposit" style="display: none">deposit</option>
</select>
The three different variances are to show what i have already tried on the select-side.
I shan't post every variation of the javascript code as it simply would be too much. I will post three variations that i tried with the three variations in the second select:
function cause_mod(){
var pool = document.getElementById("pool");
var cause = document.getElementById("cause");
var deposit = document.querySelectorAll('option[value="deposit"]');
if(pool.value === "1"){
cause.options[1].setAttribute("hidden", true)
document.getElementById("withdraw").removeAttribute("hidden")
deposit.style.display = "";
}
else if(pool.value === "2"){
pretty much the opposite
}
}
I wonder if there is any convenient method (although at this point I'll take inconvenient as well) to "grab" individual options from a select in order to .dosomething with it.
The hidden attribute shouldn't be set to the JavaScript Boolean true, it should just be present or set to the string "hidden":
const sel = document.querySelector("select");
sel.options[1].setAttribute("hidden", "hidden");
<select>
<option>Item 1</option>
<option>Item 2</option>
<option>Item 3</option>
</select>
Now, if you have an option that should not have any value, set it to: value="", not value="none" because none is a string and therefore will become the value of the element.
Also, setting the CSS style.display property to an empty string is not acceptable as this attribute should be set to a valid CSS display value.
Additionally, querySelectorAll() returns a node list, which is an array-like object. Node lists don't have a value property. In your case, if you are looking for a single element on your page, use querySelector(), which will return the first element that matches the selector you supply or undefined if no match can be found. When there is a match, you can then access its DOM properties, like value.
Lastly, you should move your pool, cause and deposit variable declarations out of your function so that they are reinitialized each time the function is called, this is a wasted of resources to scan for the same elements that you already scanned for earlier.

How to make a dropdown to select proper selected item?

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.

Selecting first option of multiple select elements by Prototype JS

I want to select first option of all the select dropdowns having class required-entry in a page with Prototype JS. I have searched through SO questions and found many relevant questions but not what I exactly needed.
Thanks
It's been quite a while since I've done any Prototype.js. So this may not be the best way to go about it, but it should work.
let's say you have a page with:
<select class='required-entry'>
<option value='a'>AAA</option>
<option value='b'>BBB</option>
<option​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ value='c'>CCC</option>
</select>
<select class='required-entry'>
<option value='x'>XXX</option>
<option value='y'>YYY</option>
<option value='z'>ZZZ</option>
</select>​
You can grab the first option for each select by doing:
var firstOptions = [];
$$('.required-entry').each(function(sel, i) {
firstOptions.push($(sel).getElementsBySelector('option')[0]);
});
// firstOptions is now an array containing the first options
Now, I couldn't tell from your question if you wanted to retrieve the first options, or set the select value so that the first option is literally selected. Here's the later:
$$('.required-entry').each(function(sel, i) {
sel.selectedIndex = 0;
});

Issues Setting Value/Label Using DropKick Javascript

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 :)

JS/Jquery: how to check whether dropdown has selected values?

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.

Categories

Resources