简体   繁体   中英

jQuery hide/show some part of the form

I have a form which I am giving a part of it in the following:

<input type="checkbox" id="yes" name="yes" value="1" />Yes

<div id="divyes">
    <div class="form-group">
        <label for="hey">Hey</label>
        <select class="form-control input-sm" id="hey" name="hey">
        </select>
    </div>
    <div class="form-group">
        <input type="text" class="form-control input-sm" id="yes2" name="yes2" />
    </div>
    <div class="form-group">
        <input type="text" class="form-control input-sm" id="yes3" name="yes3" />
    </div>
</div>

I am trying to show or hide some part of the form according to checkbox's checked statu.

$(function () {
    $("#divyes").hide();

    $("#yes").click(function () {

        if ($("#yes").attr("checked")) {
            $("#divyes").slideDown();
        } else {
            $("#divyes").slideUp();
            $("#divyes > input").text("");
        }
    });
});

You can see the fiddle here

If I select jQuery 1.8.3 from the left panel it works fine but if I select 1.10.1 it does not work. I am also using 1.10.2 on my project. So I want to know how I can do my work without using .slideDown() / .show() and .slideUp() / .show() ? In other words, is my logic good or can you offer better one?

Use the .change() event and an instance of this

$("#yes").change(function () {

    if (this.checked) {
        $("#divyes").slideDown();
    } else {
        $("#divyes").slideUp();
        $("#divyes > input").text("");
    }
});

The fail is happening on the .attr method - it should be .prop to check, however you can just do this.checked for an even faster result.

Fiddle: http://jsfiddle.net/a3j5V/4/

$(function () {
  var yes_cont = $("#divyes");
  var yes_checkbox = $("#yes");
  yes_cont.hide();
  yes_checkbox.click(function () {
    if ($(this).is(':checked')) {
        yes_cont.slideToggle('up');
    }  else {
        yes_cont.slideToggle('down');
      }
  });
});

http://jsfiddle.net/rY4Ts/15/

i made it with toggle

$('#divyes').toggle('slow');

http://jsfiddle.net/a3j5V/11/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM