Pass the selected value to the function using the jquery selector

I am a new jquery / js user trying to pass an argument from a function selector. Here are some of the code:

// function to select data var data = [ {val: 10, year: 1990}, {val: 20, year: 1991} ] var year_data = [] function select_year_data(y) { year_data = data.filter(function(d) {return d.year==y}) } 

//Selector

 <select name="Year" id = "year_menu" style="width: 230px; position: absolute; left: 400px; top: 50px"> <option value=1990>1990</option> <option value=1991>1991</option> </select> 

What I would like to do is something like this:

 <onchange>select_year_data($('#year_menu.val()') 

But I know that this is not entirely correct.

+4
source share
3 answers

Here you can use the jQuery change method Change ()

 $(function() { $('#year_menu').change(function(){ select_year_data($(this).val()) }); }); 
+5
source

like this?

 function select_year_data() { var y = $('#year_menu.val()'; year_data = data.filter(function(d) {return d.year==y}) } 
+1
source

If you use your function like $. onchange callback, then you will always have the data selected based on user selection in the year_data variable

 function select_year_data() { var y = $(this).val(); year_data = data.filter(function(d) {return d.year==y}); } // call that func on change event $('#year_menu').change(select_year_data); // or straight forward one without another function $('#year_menu').change(function(){ var y = $(this).val(); year_data = data.filter(function(d) {return d.year==y}); }); // assuming year_data and data is declared in global scope. 
+1
source

Source: https://habr.com/ru/post/1412484/


All Articles