gpt4 book ai didi

javascript - 提交表单后,Ruby on Rails 保持复选框处于选中状态

转载 作者:行者123 更新时间:2023-11-28 05:53:30 26 4
gpt4 key购买 nike

我正在 Rails 中创建一个应用程序,您可以在其中选择要显示的内容的不同类别,并且我使用表单和复选框来完成此操作,但我似乎无法让复选框在渲染后保持选中状态这一页。我的 Controller :

def select
@grants = Array.new
@cat = Array.new

@has = params[:select]

@has.each do |key, value|
if value != 'no'
@cat.push(value)
end
end

if @cat != nil
@cat.each do |cat|
@grants = @grants.concat(sortbycategory(Grant.all, cat))
end
if params[:obprice] == 'yes'
arrangebyprice(@grants)
elsif params[:obdate] == 'yes'
arrangebydate(@grants)
end
@grants = Kaminari.paginate_array(@grants).page(params[:page]).per(25)
render :partial => 'select', :layout => 'application'
else
puts 'something went wrong'
end
end

这是我在 View 中使用的复选框之一。

<form action="/allgrant/select" method="post">
<% unless are_grants?("agriculture") == false %>
<li>
<p id = 'shifter'>
<input name="select[agriculture]" type="hidden" value="no" />
<label>

<input type="checkbox" name = "select[agriculture]" value = 'agriculture'/>
Agriculture

</label>
</p>
</li>
<br>

我找到了这个 javascript 并尝试使用和修改它,但当我使用它时它会选择所有复选框或不选择任何复选框

 <script>
$(function(){
var test = localStorage.input === 'true'? true: false;
$('input').prop('checked', test);
});

$('input').on('change', function() {
localStorage.input = $(this).is(':checked');
console.log($(this).is(':checked'));
});
</script>

我也会把评论中的代码放在这里,因为它没有正确显示

<input type="checkbox" name = "select[agriculture]" value = 'agriculture' <%= @cat.include? 'agriculture' ? "checked=checked" : "" %> />

最佳答案

就在这里:

  var test = localStorage.input === 'true'? true: false;
$('input').prop('checked', test);

这就是为什么所有复选框都被选中的原因。

您有一个全局变量存储在 localStorage.input 中。

当您调用$('input').prop('checked', test)时,将选择所有输入并应用该属性。

将状态存储在 localStorage 中似乎是一种明智的方法,但您需要单独存储每个复选框的状态,并且需要单独将属性应用于每个复选框。

在以下示例中,每个复选框输入的 HTML 标记都应具有一个 id 属性,该属性是唯一标识符:

$("input[type='checkbox']").forEach(function(node){
var $input = $(node),
selector = $input.attr("id")
if (localStorage[selector]) {
$("#" + selector ).prop("checked", true)
}
})

$("input[type='checkbox']").on('change', function(e) {
var $input = $(e.currentTarget),
selector = $input.attr("id"),
isChecked = $input.is(':checked') === 'true'
nextState = !isChecked
localStorage[selector] = nextState
console.log($input.attr("id") + " is checked? " + nextState)
});

关于javascript - 提交表单后,Ruby on Rails 保持复选框处于选中状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37892885/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com