jQuery conceal input field after it has been displayed

I've created an HTML form with two different sections for search purposes. The first section displays basic fields, and by clicking on "Advanced Search" (in my case, "Расширенный поиск"), additional fields are revealed. Everything works fine until I try to hide the advanced fields - they disappear briefly but then reappear. Why is this happening?

Here's the code snippet:

  $(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)
  });

Check out the fiddle here: http://jsfiddle.net/8UV4c/

Any suggestions on how to fix this bug?

Answer №1

When you place the #advanced-search-hide div within the #advanced-search-show, both elements' event handlers will run when #advanced-search-hide is clicked. Instead of adding #advanced-search-hide, you can let #advanced-search-show 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") ? "Collapse" : "Expand Advanced Search");
      });
  });

  $(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]").prop('checked', false);
    $(this).closest('form').find("select").find("option:eq(1)").prop('selected', true)
  });

Answer №2

Try using this method

  $(document).on('click', '#show-advanced-search', function () {
  if ($("#advanced-search-area").is(':visible')) {
      $(this).text("Expand");
  } else {
      $(this).text("Collapse");
  }
  $("#advanced-search-area").slideToggle();
});

Check out the demo

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to ensure that my text always aligns perfectly to the end of the line?

I've been struggling to create a column layout where the text perfectly aligns with the end of the line, but so far, I haven't had any success. Despite my efforts to find a solution online, I have come up empty-handed. What I'm aiming for i ...

What is the best way to display a jpg image file stored on an SD card using PhoneGap?

My goal is to display a jpg image from the data directory of an Android phone, not a photo taken by the camera. Here's the code I've worked on so far: document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady(){ ...

Exploring the power of Angular by implementing nested ng-repeat functionalities:

I am currently working on an ng-repeat feature to add items from the array (album array). Everything seems to be functioning correctly. However, I also have a colors array that should assign different background-colors to the card elements of the album arr ...

Tips for inserting an item into a fresh row

Users are intended to input their question and choose answers. When they click on the "Add Question" button, the question and answer should be added. An issue arises when attempting to add an answer (You can test this in the provided fiddle by clicking he ...

Remove all instances of an empty array within a larger array

Is there a way to eliminate an empty array from within a parent array prior to adding a new element? In the structure provided, it appears as follows: var parentArray = [ ['123', '345'], [], ['12'] ] The goal is to remove t ...

Having trouble with getting the background image URL to work in Django CSS?

Hey there, I'm having an issue with my header-task class. The background-image doesn't seem to be showing up, even though when I click the URL in Visual Studio Code, the image displays. Can anyone help me figure out what's going wrong with m ...

Error message: "Angular.js encountered a typeError stating that V2.example is not a function"

Having recently started learning Angular.js, I came across a tutorial that was created about a year ago. In this tutorial, I am attempting to implement a search feature that takes user input and searches for it on Github.com. Below is the HTML code snippet ...

What is the best way to show emojis in AngularJS?

Recently starting to work with angularjs, I've incorporated "emoji-min.js" and "emoji-min.css" into my project as an attempt to display emojis within a text field. Despite my efforts, the emojis are not displaying as intended. Here is a snippet of my ...

Tips for creating responsive jQuery autocomplete list items

I've created a website using Bootstrap 4 and integrated JQuery autocomplete. However, the list items in the autocomplete feature are not responding well to different screen sizes. Take a look at my code below: jQuery(document).ready(function ($) { ...

The inner workings of JavaScript functions

I am curious about how JavaScript functions are executed and in what order. Let's consider a scenario with the following JavaScript functions: <span id=indicator></span> function BlockOne(){ var textToWrite = document.createTextNode ...

The start "NaN" is not valid for the timeline in vis.js

Whenever I attempt to make a call, an error message pops up saying Error: Invalid start "NaN". I've looked everywhere online for a solution with no success. Below are the timeline options: timeline: { stack: true, start: new Date(), end: ...

Change the color of the first element when hovering over any of its siblings using only CSS

I am looking for a solution using only CSS We have 3 circles here. When I hover over circles with the class name "Mycircle", the circle with the class name "BigCircle" should change to red color HTML <div class="BigCircle"></div> <div cl ...

HTML code for adding a dropdown menu inside a table cell

I am trying to set up a table where one cell functions as a dropdown menu. The data.field is being fetched from the backend and I want it to be displayed during rendering. Additionally, a fList is also retrieved from the backend. When a user clicks on th ...

Incorporating SASS/SCSS syntax within the <style> element

Can I include SASS/SCSS syntax directly in an .html file within a style tag? I'm interested in defining a variable within the .html file and then utilizing it in a .sass file. ...

Is there a Problem with Paging in Meteor with Jquery?

I implemented Pagination using Jquery, but I encountered an issue along with the following error message: Uncaught TypeError: Object [object Object] has no method 'customPaginate' I am unsure how to resolve this problem. Could you please take ...

Unexpected updates occurring in custom Google Sheet functions

Currently, I am utilizing a personalized function to retrieve price data for EVE Online. However, I am encountering an issue where the function is updating every 10-20 minutes, leading to a depletion of my daily URL Fetches quota. The primary function can ...

When attempting to use the search bar to filter in ReactJs, an error occurs: TypeError - Unable to access properties of undefined (specifically 'filter')

When I receive data from my JSON server on the console, everything looks good. But when I try to type something in order to filter it, an unhandled error occurs with the message: 1 of 1 Unhandled Error Unhandled Runtime Error: TypeError: Cannot read prop ...

Displaying all items in a collection as HTML using Node.js

I am looking to showcase all the items in my mongodb collection as HTML. In the past, I have accomplished this with simpler tasks, such as... router.get('/', function (req, res) { res.render('home', { title: 'Express', u ...

A guide to displaying a JSON object in a Jade template and iterating through the data

When I pass a JSON string to a jade file for rendering, I am facing an issue where I can only print the entire string and not its individual elements. How can I print specific elements or iterate through the JSON string? app.js: var http = require(&ap ...

The search filter in react material-table is not functioning properly upon initialization

Search functionality is functioning correctly in this code snippet: <MaterialTable columns={[ { title: 'Name', field: 'firstname', type: 'string' } ]} /> Unfortunately, the Search filte ...