How can my forms checkboxes keep their state after

2019-09-18 13:50发布

问题:

I have a form consisting of checkboxes which is filtering records on an index page, how can I make the checkboxes in the form keep their checked state once the form is submitted and the page is reloaded?

I'm already using jQuery-UI to make the checkboxes look better. Im super new to any kind of programming and having less luck with javascript.

index.html.erb

<script>    
  $(function() {
    $(".areas").buttonset();
  });

  $(function() {
    $( "button, input:submit, a", ".filter_form_button" ).button();
    $( "a", ".form_filter_button" ).click(function() { return false; });
  });
</script>

<div class="filter_options_container">
  <%= form_tag '', :method => :get, :id => 'filter_form' do %>        

    <fieldset class="filter_form_fieldset areas">
      <% Area.all.each do |a| %>
        <p class="area_check"><%= check_box_tag 'areas[]', a.id, false, :id => "area-#{a.id}" %>
        <label for="area-<%= a.id %>"><p1><%= a.name %></p1></label></p>
      <% end %>
    </fieldset>

    <div class="filter_form_button">
      <p2><input type="submit" value="Filter"/></p2>
    </div>
  <% end %>
</div>

Any help with this is much appreciated!

回答1:

I found this jQuery plugin that keeps the form filled in when you leave and come back. Seems to work really well. dumbFormState



回答2:

You have to save their state somewhere, and then load their state whenever you instantiate the checkboxes. This might help: http://www.webdevelopersnotes.com/tips/html/finding_the_value_of_a_checkbox.php3

The reality, however, is that you need a design that allow you to save the "current state" of a page.



回答3:

get the states of your check boxes when form submit . then pass it to the view . set the values via jquery .

like you get a check box's checked valuve is 2 when submit the form , then you get it and pass to the view

$this->view->checkbox1 = 2 ;

then in jaquery

var val = <?php echo $this->checkbox1 ; ?>;

$("#mycheckbox")[val].checked = true;