How to only show input fields if checkbox is checked?

前端 未结 6 2239
小鲜肉
小鲜肉 2021-01-02 12:40

Basically, I want to only show these fields if checkbox is selected, if it becomes unselected, disappear.



        
相关标签:
6条回答
  • 2021-01-02 13:29

    The "#foo" selector looks for elements whose id value is "foo", not "name". Thus the first thing you need to do is add an "id" attribute to your checkbox.

    The second thing to worry about is the fact that, in IE (at least old versions), the "change" event isn't fired until the checkbox element loses focus. It's better to handle "click", and what you want to check is the "checked" attribute of the element.

    What I'd write is something like:

    $('#supplied').click(function() {
      $('.date')[this.checked ? "show" : "hide"]();
    });
    
    0 讨论(0)
  • 2021-01-02 13:32

    Matthews answer works great just that the .live deprecated in jQuery 1.7 use the .on

    $('#supplied').on('change', function(){
        if ( $(this).is(':checked') ) {
            $('#date').show();
        } else {
            $('#date').hide();
        }
    });
    
    0 讨论(0)
  • 2021-01-02 13:35

    Pointy pointed out that you need to set the id of our checkbox (or use a name selector). You also need to use #date (id) instead of .date (class) (or again change the HTML).

    Working demo

    0 讨论(0)
  • 2021-01-02 13:43

    Try this:

    $('input[name=supplied]').live('change', function(){
         if ( $(this).is(":checked")) {
             $('#date').show();
         } else {
             $('#date').hide();
         }
     });
    
    0 讨论(0)
  • 2021-01-02 13:44

    You can do this with pure CSS3, of course:

    :checked + #date { display: block; }
    #date { display: none; }
    

    The equivalent selectors ought to work just fine in jQuery as well.

    0 讨论(0)
  • 2021-01-02 13:45

    Try something like:

    $('#supplied').live('change', function(){
         if ( $(this).attr("checked")) {
             $('.date').show();
         } else {
             $('.date').hide();
         }
     });
    
    0 讨论(0)
提交回复
热议问题