JQuery trigger event for checkbox

I have a number of checkboxes for which I wrote a jquery script on click. When a user clicks on a flag, he opens another series of flags, and it continues. Now my problem is that users check some of these checkboxes and go to the next page, and for some reason it comes back to the page. Then I must have all the boxes that he / she checked to open. I wrote a check check when dom loads

$(document).ready(function(){ if($('.main').is(':checked')){ $(this).trigger('click'); }else{ //do nothing } $('.main').click(function(){ if($('.main').is(':checked')){ var val = $(this).attr('alt'); $('#'+val).show(); }else{ var val = $(this).attr('alt'); $('#'+val).hide(); } }); }); 

As you see above. Home is the flag class. After that, I open another series of flags. Now I want this to be automatically executed for their marked mailboxes when they visit the page again.

+6
source share
3 answers

use a session or cookie to save .main class flag values ​​and check them accordingly when returning, then use the following code:

 <script type="text/javascript"> $(document).ready(function(){ $('.main').each(function(){ if($(this).is(':checked')){ var val = $(this).attr('alt'); $('#'+val).show(); }else{ var val = $(this).attr('alt'); $('#'+val).hide(); } }); if($('.main').is(':checked')){ $(this).trigger('click'); }else{ //do nothing } $('.main').click(function(){ if($('.main').is(':checked')){ var val = $(this).attr('alt'); $('#'+val).show(); }else{ var val = $(this).attr('alt'); $('#'+val).hide(); } }); }); </script> 
+3
source

I would just use JSON and local storage to keep track of which fields were checked, etc.

 $(document).ready(function () { if (localStorage.getItem('boxes')) { var boxes = JSON.parse(localStorage.getItem('boxes')); $.each(boxes, function (idx, val) { var box = $('.main').eq(idx); box.prop('checked', val); $('#' + box.attr('alt')).toggle(val); }); } $('.main').on('change', function () { var val = $(this).attr('alt'), boxes = {}; $.each($('.main'), function (i, el) { boxes[$(el).index('.main')] = el.checked; }); $('#' + val).toggle(this.checked); localStorage.setItem('boxes', JSON.stringify(boxes)); }); }); 

DEMONSTRATION

+1
source

This is usually a browser that decides to β€œhelp” and replenish forms that the user has already completed. You should not rely on the browser, as this parameter can be easily changed and may vary from user to user.

Instead, you might consider saving the checked checkboxes in a cookie / localstorage, or perhaps sending each click through AJAX to your server. Then, when the user lands on the page, you can check the contents of your cookie or download items that have been saved through AJAX; Then you can recreate clicks on the corresponding elements.

Highlight this linked post for processing cookies using jQuery - How to set / delete a cookie using jQuery?

0
source

Source: https://habr.com/ru/post/943856/


All Articles