Update variable in JS based on selected option from dropdown - javascript

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>

Related

Dropdown in HTML is empty at initialization due to Javascript

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>

How to always trigger function of <select> tag

I wrote a select tag (have default selected) and take the option value to trigger another js function:
var selectElement = document.getElementById("sel");
function somefunction() {
console.log(selectElement.value);
};
<select id="sel" onchange='somefunction()'>
<option selected="selected" value='yes'>Yes</option>
<option value='no'>No</option>
<option value='all'>All</option>
</select>
However, if I keep the onchange event, it only triggers the function when I change the selection. I also want to trigger the function when page is loaded with the default selection that i have set (which is Yes in the above example).
Thanks.
Add an onload function to your body tag:
<body onLoad='somefunction()'>
What I would recommend is to build an independent function for calculating the selected index. Then I would manually map a variable to the <select> element, and attach an onchange() handler than calls this function, passing itself in as a parameter.
With this setup, you have both a function to calculate the selected value of any <select> element, and the target <select> element already mapped to a variable for easy access. You can then simply pass that variable into the function on page load:
/* Function to grab the selection, which takes a `<select>` element as a parameter */
function getSelectedIndexes(select) {
for (var i = 0; i < select.options.length; i++) {
if (select.options[i].selected) {
return i;
}
}
}
var select = document.getElementsByTagName("select")[0];
select.onchange = function(e) {
console.log(getSelectedIndexes(this)); // Selection on change
}
console.log(getSelectedIndexes(select)); // Default selection
<select>
<option disabled selected> Select
</option>
<option selected="selected" value='yes'> Yes
</option>
<option value='no'> No
</option>
<option value='all'> All
</option>
</select>
Hope this helps! :)
Why don't you call the function when the window is loaded? I guess that will solve
your problem.
window.onload = function() {
if (selectEl.value) // or use (selectEl.value == "yes)
somefunction()
};
var selectEl = document.getElementById("sel");
function somefunction() {
console.log(selectEl.value);
}
<select id="sel" onchange='somefunction()'>
<option selected="selected" value='yes'>Yes</option>
<option value='no'>No</option>
<option value='all'>All</option>
</select>

how to retain selected value on refreshing page?

jquery
(function($) {
$(document).ready( function() {
$('#client-list').change(function() {
$(this).attr("selected", true);
location.reload();
});
});
});
dropdown list
<select id="client-list">
<option value="Choose-Client">Choose Client</option>
<option value="client1" >Client 1</option>
<option value="client2" >Client 2</option>
<option value="client3" >Client 3</option>
<option value="client4" >Client 4</option>
</select>
how can i retain selected value and reload the page onchange dropdown?
Store you values in localStorage
First fetch value from localStorage and set it as value of your select, if it's undefined (when run the first time), it will fall back to first element in your select.
If it is defined, then your select will have value from localStorage as selected value.
On change, update your value in localStorage
(function($) {
const selection = localStorage.getItem('selection');
$(document).ready( function() {
let $clientList = $('#client-list');
$clientList.val(selection);
$clientList.change(function() {
localStorage.setItem('selection', $(this).val());
});
});
});
You can do this using cookies in Jquery by using a plugin.
https://github.com/js-cookie/js-cookie
Download the plugin and include it in your project
<script src="/path/to/js.cookie.js"></script>
To set cookie
Cookies.set('name', 'value');
To read cookie
Cookies.get('name'); // => 'value'

JQuery , syncronized selection option

I have to tag in my jsp with two identical select option.
I want that anytime I am chaining one , the second (that is in the bottom ) will change too.
<select class="groups">
<option class='America' value='America'>America</option>
<option class='Europe' value='Europe'>Europe</option>
<option class='Asia' value='Asia'>Asia</option>
<select>
<select class="groups">
<option class='America' value='America'>America</option>
<option class='Europe' value='Europe'>Europe</option>
<option class='Asia' value='Asia'>Asia</option>
<select>
So for instance anytime I am choosing Europe ( or any other ) I want all of my select get updated with the same value.
without jquery:
document.getElementsByClassName("groups").forEach(function(element){
element.onchange = function(event) {
document.getElementsByClassName("groups").forEach(function(x){
x.value = event.target.value;
});
}
});
with jquery:
$('.groups').onchange = function(e){
$('.groups').forEach(function(x){
x.val(e.currentTarget().val)
});
}

Selecting multiple value from a dropdown and call a javaScript function

I know I can create a multiple select dorpdown like this -
<select name="city" multiple>
<option value="Dallas">Dallas</option>
<option value="New York">New York</option>
<option value="Kansas">Kansas</option>
<option value="Massachusetts">Massachusetts</option>
</select>
Using this multiple select dropdown I can select multiple city from. But can I select a javascript method separately for each of the city?
Thanks in advance.
You can get the value using jQuery '.val()' function.
Jquery.fn.val()
You can see how it works in the following example:
http://jsfiddle.net/uoL3s610/
$(document).ready(function(){
$('[name="city"]').change(function(){
$('#selected_container').text($('[name="city"]').val());
});
});
Or this example
http://jsfiddle.net/uoL3s610/1/
$(document).ready(function(){
$('[name="city"]').change(function(){
$('#selected_container').text('');
$.each($('[name="city"]').val(),function(index,value){
$('#selected_container').text($('#selected_container').text() + ', ' + value)
});
});
});
You are able to store the selected value of your dropdownlist in a variable and then continue with an If-structure or a switch:
$("city:selected").each(function () {
switch($(this).val()){
case "city1":
break;
}
});

Categories

Resources