byCoder
byCoder

Reputation: 9184

jQuery hide form field after there are shown

I have html form with two "sub-parts".

I do it for search purposes: for example first i see only basic field, and when i click detailed (in my case "Расширенный поиск") i see other fields, all is ok. But when i try to hide this detailed fields there are hiding, but then they roll back, but why ?

code:

  $(document).on('click', '#advanced-search-show', function (){
    $("#advanced-search-show-area" ).show("slow");
    $("#advanced-search-show").html("<span id='advanced-search-hide'>Свернуть</span>");
  });

  $(document).on('click', '#advanced-search-hide', function (){
    $("#advanced-search-show-area" ).hide("slow");
    $("#advanced-search-show").html("<span id='advanced-search-show'>Расширенный поиск</span>");
  });

  $(document).on('click', '#reset-form', function (){
    $(this).closest('form').find("input[type=text], textarea, input[type=number]").val("");
    $(this).closest('form').find("input[type=checkbox]").attr('checked', false);
    $(this).closest('form').find("input[type=select] option:eq(1)").prop('selected', true)
  });

and fiddle: http://jsfiddle.net/8UV4c/

How to solve this bug?

Upvotes: 0

Views: 115

Answers (2)

Alethes
Alethes

Reputation: 922

You're placing #advanced-search-hide div within #advanced-search-show. This causes both elements' event handlers to run when #advanced-search-hide is clicked. There's no need to add #advanced-search-hide because #advanced-search-show can handle toggling between both states easily:

  $(document).on('click', '#advanced-search-show', function (){
      var adv = $("#advanced-search-show-area" );
      _this = $(this);
      adv.toggle("slow", function(){
          _this.html(adv.is(":visible") ? "Свернуть" : "Расширенный поиск Очистить");
      });
  });

  $(document).on('click', '#reset-form', function (){
    $(this).closest('form').find("input[type=text], textarea, input[type=number]").val("");
    $(this).closest('form').find("input[type=checkbox]").attr('checked', false);
    $(this).closest('form').find("input[type=select] option:eq(1)").prop('selected', true)
  });

Upvotes: 3

Anoop Joshi P
Anoop Joshi P

Reputation: 25527

Use like this

  $(document).on('click', '#advanced-search-show', function () {
  if ($("#advanced-search-show-area").is(':visible')) {
      $(this).html("Расширенный");
  } else {
      $(this).html("Свернуть");
  }
  $("#advanced-search-show-area").slideToggle();


});

Demo

Upvotes: 0

Related Questions