我有一个在Rails应用程序中显示下拉列表的select标记。我希望能够使用jQuery根据选择元素的选择来显示和隐藏div。我不能让它工作,我相信这是由于turbolinks不能很好地与jQuery合作。当我编辑一个现有的记录时,该记录的下拉列表被选择为正确的选项('Cheque'),字段显示为我想要的样子。但是,当我创建一个新的记录,并从下拉菜单中选择选项时,它不会像我希望的那样显示隐藏的div。
我尝试将turbo链接的数据属性添加到false,但它不起作用。
<%= f.select :payment_method, @payment_methods, {:include_blank => true}, { :class => 'form-control', :id => 'payment-method', 'data-turbolinks'=>'false' } %>当然,我所有的jQuery都包含在:
$(document).on('turbolinks:load', function() {
function vanish(x) {
x.css('display', 'none');
}
function reappear(x) {
x.css('display', 'block');
}
// for showing cheque number field if payment method is cheque
vanish($('#cheque-number-section'));
if ($("#payment-method option:selected").text() == "Cheque") {
reappear($('#cheque-number-section'));
} else {
vanish($('#cheque-number-section'));
}
});发布于 2018-02-05 02:30:40
dstull的评论让我找到了答案。必须检查select元素的更改!
$("#payment-method").on('change', function() {
if($("#payment-method option:selected").text() == "Cheque"){
reappear($('#cheque-number-section'));
} else {
vanish($('#cheque-number-section'));
}
});发布于 2018-02-05 02:14:35
试试这个:
$(document).on('ready turbolinks:load', function(){
// wrap your code here
})https://stackoverflow.com/questions/48611350
复制相似问题