I've created in an html webpage a dropdown with four options. It worked well but I realized that when the page was refreshed, the value would reset itself to the first option. Since I wanted the user's choice to be kept in memory, I added a javascript code snippet that I found somewhere.
It works very well, except that at the initialization the default value of the dropdown is an empty field.
I would need the first option to be displayed at initialization.
I guess it's easy but I don't know JavaScript at all. Could you please help?
Here is what the code looks like:
<select name="options" id='dropdown'>
<option value="1">1st Option</option>
<option value="2">2nd Option</option>
<option value="3">3rd Option</option>
<option value="4">4th Option</option>
</select>
<!-- The script below helps to keep in memory the dropdown value after the page has been refreshed -->
<script type="text/javascript">
var selectedItem = sessionStorage.getItem("SelectedItem");
$('#dropdown').val(selectedItem);
$('#dropdown').change(function() {
var dropVal = $(this).val();
sessionStorage.setItem("SelectedItem", dropVal);
});
</script>
I think you should check if SessionStorage Key exists or not.
I have created working example of your code : https://jsfiddle.net/vieckys/Lwv1n8p7/7/
Here is HTML Markup:
<select name="options" id='dropdown'>
<option value="0" selected>--- select here ---</option>
<option value="1">1st Option</option>
<option value="2">2nd Option</option>
<option value="3">3rd Option</option>
<option value="4">4th Option</option>
</select>
and JS Code
let selectedItem = sessionStorage.getItem("SelectedItem");
if (selectedItem) {
$('#dropdown').val(selectedItem);
} else {
$('#dropdown').val(0);
}
$('#dropdown').change(function() {
let dropVal = $(this).val();
sessionStorage.setItem("SelectedItem", dropVal);
});
Let me know if you face any issue with this.
Based on your scenario, you can explicitly trigger the change event after the value is set for the dropdown using trigger('change') on the select dropdown. This will run the change function and will save the initial value in the sessionStorage. So, add this line of code, $('#dropdown').trigger('change') something like:
<script type = "text/javascript" >
var selectedItem = sessionStorage.getItem("SelectedItem");
$('#dropdown').val(selectedItem);
$('#dropdown').change(function() {
var dropVal = $(this).val();
sessionStorage.setItem("SelectedItem", dropVal);
});
$('#dropdown').trigger('change'); // trigger the change explicitly
</script>
Related
I have this dropdown, where I want to change the variable in my js script based on which option is selected. The variable is send to another function which updates the page.
My html file:
//My JS function that is trying to access the data from the dropdown
function updateDD(){
$(".sheetnameSelect").change(function(){
return $(this).find(":selected").text()
})
}
//I want to use that function to update another variable based on selected option
var selected = updateDD()
alert(selected)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class='sheetnameSelect'>
<option value="Cars">Cars</option>
<option value="Homes">Homes</option>
<option value="Planes">Planes</option>
</select>
However the function updateDD() is not returning the selected option (both when the pages loads or when I select different option)
You might not need to return the value, you can call the method whenever there is a change in select:
$(".sheetnameSelect").on('change', function() {
var selected = $(this).val();
createTable(selected);
});
function createTable(value) {
console.log(value);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class='sheetnameSelect'>
<option value="Cars">Cars</option>
<option value="Homes">Homes</option>
<option value="Planes">Planes</option>
</select>
I'm trying to use jquery to select the option value of the selected element in an html dropdown.
HTML
<select class="select1">
<option value ="0">" + state.greens[0].name + "</option>
<option value ="1">" + state.greens[1].name + "</option>
<option value ="2">" + state.greens[2].name + "</option>
</select>
The option values represent an index position in an array that I can load to generate additional data about objects within them.
I'm trying to use jquery to grab the option value of whatever dropdown element is currently selected.
Right now I'm using this code but it's not working:
JQUERY
var a = $(".select1 option:selected");
However it's not bringing back "1", "2", "3", etc.
When I run console.log(a) I get the following:
Not sure what's happening.
The idea is that I can use the variable a to load data like state.greens[a].price, state.greens[a].ingredients, etc.
You are almost there. Just give:
var a = $(".select1 option:selected").attr("value");
Or give this:
var a = $(".select1").val();
You need to get the value of the <select>.
var a = $(".select1").val(); // is the simple solution
Try this..
HTML
<select class="select1" id="select1">
<option value ="0">Option 1</option>
<option value ="1">Option 2</option>
<option value ="2">Option 3</option>
</select>
Pure Javascript solution
document.getElementById("select1").addEventListener("change", function(){
var a = document.getElementById("select1").value;
alert(a);
});
Check out this Fiddle
Snippet
document.getElementById("select1").addEventListener("change", function(){
var a = document.getElementById("select1").value;
alert(a);
});
<select class="select1" id="select1">
<option value ="0">Option 1</option>
<option value ="1">Option 2</option>
<option valuae ="2">Option 3</option>
</select>
In the following select box:
var sval=1;
function foo(v) {
sval=Number(v);
}
...
<select name="sval" onchange="
if (confirm('...?')) foo(this.value); else $(this).val(sval);">
<option value="1">1
<option value="2">2
<option value="3">3
The idea is to confirm the selected item change. If not confirmed to change back to the old value.
if confirm returns true, all is working as expected
if confirm returns false, then the select always gets value 1, regardles of sval
Why changing the selected item does not work from inside the onchange handler?
EDIT: The following code based on ejay_francisco's answer does the proper job:
http://jsfiddle.net/4wCQh/33/
var vals = 1;
$("#svalue").change(function() {
if (confirm('...?'))
vals=Number(this.value);
else
$(this).val(vals);
});
but its not clear what is the reason that the inline code $(this).val(sval) resets the select to 1
I've modified your code and this is how i've done it
Working Fiddle :
Javascript :
$( "#svalue" ).change(function() {
if (confirm('...?')) {
vals =$('#svalue').val();
$('#svalue').val(this.options[this.selectedIndex].value);
}else{
$('#svalue').val(vals);
}
});
HTML :
<select id="svalue">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
EDITED :
here's how its done inline : working Fiddle
HTML:
<select name="sval" onchange="if (confirm('...?')) {foo(this.value);sval=(this.value);} else $(this).val(sval);">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
Javascript :
var sval=1;
function foo(v) {
$('#svalue').val(v);
}
apparently you forgot to change the value of sval to whatever the user has previously clicked. the code is sval=(this.value); on the onchange part.
Try
I think else part is not neccessary
Change to
<select name="sval" onchange="
if (confirm('...?')) foo(this.value);">
Your approach is absolutely horrible.
When ever you inline JavaScript events on elements it just looks ugly.
Why are you wanting to set the select value to the value it has as the currently selected value?
Could you just skip this $(this).val(sval = this.value;); and only have this sval = this.value;
I'm just really a huge fan as to keeping the code and values to a bare minimum where variables are not needed and also where code is not needed.
Give this a shot.
<script type="text/javascript">
var sval = 1;
var foo = function () {
if(confirm('...?')) {
$(this).val(sval = this.value);
}
else
{
$(this).val(sval);
}
};
setTimeout(function () {
document.getElementById('sval').onchange = foo;
}, 100);
</script>
<select id="sval">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
I have found the reason the code is not working.
It came out that there are differences between execution in fiddle and browser which made tracking the problem harder.
In the inline code of the onchange event a variable with the same name as name="sval" gets defined and because the name is the same with the integer variable from the global context, the code is not using the proper value to change select's value.
This is really odd, but I am probably missing something simple. I have a simple select statement where a user can choose a value.
onChange calls a function getDrop2() which currently I am trying to get it to alert me which option is chosen.
my html is:
<select onChange= "getDrop2()" id = "drop1" >
<option value="0">All</option>
<option value="1">Alphabetical</option>
<option value="2">Brewery</option>
<option value="3">Style</option>
</select>
My Javascript is:
function getDrop2(){
var choice = $("#drop1").val()
alert(choice);
}
The output of the alert statement is just blank.
In jQuery, you're better off doing something like:
<select id = "drop1" >
<option value="0">All</option>
<option value="1">Alphabetical</option>
<option value="2">Brewery</option>
<option value="3">Style</option>
</select>
With the following JavaScript:
$(function(){
$('#drop1').change(function() {
var choice = $(this).val();
alert(choice);
}
});
The idea is that jQuery is now attaching the change function automatically to the select with the id of "drop1" By using this pattern, you've decoupled the HTML from the JavaScript that's doing the business logic.
Although what others have selected is a better approach. My answer is just to tell you why your code is not working
Try this
var choice = $('#drop1 option:selected').val()
Instead of
var choice = $("#drop1").val()
I have html drop down list,which has country list. Now I want to set current country as a default value of list. I found the JavaScript code for get country using Geolocation.
My code:
function getCountry(var name) {
if(name==geoip_country_name()) {
return "selected";
}
}
Then I need to set the selected attribute of the option list.
I tried this:
<option value="Sri Lanka" selected="getCountry('sri Lanka')">Sri Lanka</option>
But this is not correct.
Basically I want to set selected attribute value using JavaScript function
How do I do that?
Use the window.onload event, and just set the dropdown's value. Keep in mind that your hard coded country names may differ from the geo service.
<script>
window.onload = function(){
document.getElementById("country").value = geoip_country_name();
}
</script>
<select id="country" name="country">
<option value="Sri Lanka">Sri Lanka</option>
<option value="UK">UK</option>
<option value="USA">USA</option>
<select>
Basically you can do it like this:
<html>
<body>
<select id="country">
<option id="germany" value="Germany">DE</option>
<option id="uk" value="UK">UK</option>
<option id="usa" value="USA">USA</option>
</select>
<script>
var selectedCountry = 'uk'; //getCountry
var index = document.getElementById(selectedCountry).index;
document.getElementById("country").selectedIndex=index;
</script>
Start the script after your select is rendered.
Note, that this example might not be best practice. I'm also not sure if it works in all browsers (Opera works). You might use an appropriate framework like JQuery, Mootools, ...
The selected attribute is not automatically evaluated as JS code. Assuming you have stored the desired country name in the variable country, could try this instead:
var country = "Sri Lanka";
var select = document.getElementById('myselect'); //Change to the ID of your select element
for (var i = 0; i < select.options.length; i++){
if(select.options[i].value == country)
select.selectedIndex = i;
}
If you are using JQuery following line should solve your problem:
$('select').val(geoip_country_name());
If geoip_country_name returns names in lower case, While initializing the select list, value for each option be in lower case.