admin管理员组

文章数量:1294341

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.

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.

Share Improve this question edited Jan 15, 2014 at 23:39 BenMorel 36.6k51 gold badges205 silver badges336 bronze badges asked May 15, 2012 at 5:22 mikemike 23.8k32 gold badges81 silver badges100 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

Jquery change method can be used here Change()

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

like this?

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

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.

本文标签: javascriptPass selected value to function using jquery selectorStack Overflow