mike
mike

Reputation: 23811

Pass selected value to function using jquery selector

I am a new jquery/js user trying to pass an argument from a selector to a function. Here is 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 isn't quite right.

Upvotes: 4

Views: 8369

Answers (3)

Prasenjit Kumar Nag
Prasenjit Kumar Nag

Reputation: 13461

If you use your function as $.onchange 's callback then you will always have the data selected based on users selection on the variable year_data

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.

Upvotes: 1

Tiago Peczenyj
Tiago Peczenyj

Reputation: 4623

like this?

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

Upvotes: 1

Ravi Gadag
Ravi Gadag

Reputation: 15851

Jquery change method can be used here Change()

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

Upvotes: 5

Related Questions