if check box is checked display div

2019-03-21 15:38发布

I'm trying to build something like wordpress options for toggling fields visibility when creating and article. What I've build is relying on the $.click function that is toggling the parent with the corresponding field name and I was wondering what would be the best way of doing this with if the check box is checked because my code will mess up if you check a box and reload the page because its a click and not if the box is actually 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();
});

3条回答
唯我独甜
2楼-- · 2019-03-21 15:44

I think this, Jquery UI Save State Using Cookie, is the missing part you are after to control state between reloads?

查看更多
三岁会撩人
3楼-- · 2019-03-21 15:55

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
});
查看更多
该账号已被封号
4楼-- · 2019-03-21 15:59

Assuming that you are externally controlling the checked state of your checkboxes...

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

In other words, whatever state the checkboxes are in will be evaluated when the page loads, so if a box is not checked, the corresponding element will start out hidden. So if you are setting a value server-side which checks the box, this client-side JavaScript should evaluate it properly.

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 my use of data-* attributes. This avoids using the name attribute of one field to indicate a relationship to another field. You can legally name these attributes whatever you want, as long as they are prefixed with data-.

查看更多
登录 后发表回答