if check box is checked display div

后端 未结 3 2020
庸人自扰
庸人自扰 2021-02-10 14:57

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

3条回答
  •  独厮守ぢ
    2021-02-10 15:40

    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

    
    Title
    
    
    
    Title

    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-.

提交回复
热议问题