If display div is checked

I am trying to create something like wordpress options for the visibility of fields when creating and article. What I built relies on the $.click function, which toggles the parent with the corresponding field name, and I was wondering how best to do this if the checkbox is checked, because my code will go bad if you check the box and reload the page, because its click is not there if the checkbox is really checked. Thanks in advance!

http://jsfiddle.net/zgrRd/1/

HTML

 <input type="checkbox" name="title"> <span class="caption">Title</span> <div class="hidden"> <h2>Title</h2> <input type="text" name="title"> <span class="caption">Lorem</span> </div> 

JQuery

 $('input[type="checkbox"]').click(function(){ var item = $(this).attr('name'); $('input[name="'+item+'"][type="text"]').parent().toggle(); }); 
+4
source share
3 answers

Assuming you are in control of the controlled state of your flags ...

Demo: http://jsfiddle.net/zgrRd/5/

In other words, any state in which the flags are located will be evaluated when the page loads, therefore, if the check box is not selected, the corresponding element will begin to hide. Therefore, if you set a value on the server side that checks the checkbox, this client-side JavaScript must evaluate it correctly.

Javascript

 function evaluate(){ var item = $(this); var relatedItem = $("#" + item.attr("data-related-item")).parent(); if(item.is(":checked")){ relatedItem.fadeIn(); }else{ relatedItem.fadeOut(); } } $('input[type="checkbox"]').click(evaluate).each(evaluate); 

HTML

 <input type="checkbox" data-related-item="title1"> <span class="caption">Title</span> <div class="hidden"> <h2>Title</h2> <input type="text" id="title1"> <span class="caption">Lorem</span> </div> <hr> <input type="checkbox" data-related-item="title2" checked> <span class="caption">Title</span> <div class="hidden"> <h2>Title</h2> <input type="text" id="title2"> <span class="caption">Lorem</span> </div> 

Note the use of data-* attributes. This avoids the use of the name attribute of one field to indicate a relationship to another field. You can legally name these attributes as you wish if they are prefixed with data- .

+8
source

I think this is a jQuery UI Save State Using Cookie - the missing part that you use to manage state between reloads?

0
source

HTML

 <input type="checkbox" id="cbxShowHide"/><label for="cbxShowHide">Show/Hide</label> <div id="block">Some text here</div> 

CSS

 #block{display:none;background:#eef;padding:10px;text-align:center;} 

javascript / jquery

 $('#cbxShowHide').click(function(){ this.checked?$('#block').show(1000):$('#block').hide(1000); //time for show }); 
0
source

All Articles