<%= date_select(:production_month, :date, order: [:month, :year], :start_year => @start_year, :end_year => @end_year) %>
我在一种Rails表单中都具有上述date_select。
当上述date_selected的值更改时,我希望调用javascript函数。
我在代码中编写了以下javascript块来处理此问题:
$('#production_month').change(function () {alert("Yayyy!!!")});
但是无论我在date_select中选择什么值,都永远不会调用此javascript函数。
我在这里做错了什么?请帮忙!
答案 0 :(得分:1)
通过内置的rails方法执行此操作可能会更容易:
Rails 3 & Ajax date_select onchange => submit
date_select(object_name, method, options = {}, html_options = {})
在您的情况下:
<%= date_select(:production_month, :date, order: [:month, :year], :start_year => @start_year, :end_year => @end_year, html_options: { onchange: 'productionMonth();' } ) %>
编辑:或使用我误读的正确方法名称:
<%= date_select(:production_month, :date, order: [:month, :year], :start_year => @start_year, :end_year => @end_year, html_options: { onchange: 'fire_on_product_change();' } ) %>
答案 1 :(得分:1)
您可以通过在浏览器中检查元素来获取id
元素,也可以显式设置id
。
<%= date_select(:production_month, :date, order: [:month, :year], :start_year => @start_year, :end_year => @end_year, html_options: {id: 'production_month', class: 'my_css_class'}) %>
然后在jQuery事件中使用此ID
$('#production_month').change(function () {alert("Yayyy!!!")});
或者,您也可以尝试
通过onchange: 'method();'
中的html_options
<%= date_select(:production_month, :date, order: [:month, :year], :start_year => @start_year, :end_year => @end_year, html_options: { onchange: 'fire_on_product_change(this.id);' } ) %>
然后为事件定义jQuery方法fire_on_product_change
<script type="text/javascript">
function fire_on_product_change(id){
var id = id;
// Use jQuery to get any other attribute using id
// $("#id").val()
alert("Yayyy!!!");
})
</script>