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

Guide to showing an uploaded image in a child component using Vue.js

Using the v-file-input component from Vuetify, I am able to upload images with the following code: <v-file-input label="Image" filled accept="image/png, image/jpeg, image/bmp" prepend-icon="mdi-camera" v-mod ...

Issues following compilation with npm run prod

I am currently working on a small website using Laravel and Tailwind CSS on shared hosting. While I am able to use a command line tool on the host, I have encountered an issue. In my local environment, Tailwind works perfectly fine. However, after running ...

What is the process for converting HTML assets into a SCORM package?

**css styles fonts images media menu1_images menu2_images menu3_images menu4_images** index.html index_custom.js index_actions.js menu1.html menu1_custom.js menu1_actions.js menu2.html menu2_custom.js menu2_actions.js menu3.html menu3_custom.js menu3_actio ...

Creating a three-column layout with position fixed in the center

I'm struggling with achieving a maximum width of 400px for the entire set of three columns and centering them. ---------------------------------------------------- | | | |----------------------------- ...

Adjusting the visible options in ngOptions causes a disruption in the selected value of the dropdown menu

I have successfully implemented a feature that allows users to convert temperature values displayed in a drop-down menu to either Celsius or Fahrenheit. For this functionality, I am using a select input with ng-options as shown below: <select ng-model ...

The declaration file for module 'react/jsx-runtime' could not be located

While using material-ui in a react project with a typescript template, everything is functioning well. However, I have encountered an issue where multiple lines of code are showing red lines as the code renders. The error message being displayed is: Coul ...

Disabling the authentication prompt in the browser

Apologies for the repetition, but I would like to pose a more general question. Is there any method on the client side of a web application to predict if requesting a resource will result in a 401 status code and trigger an unattractive authentication pro ...

Navigating Your Way Through the Center (ASP.NET MVC)

My navbar has elements that I want to center within it, but using margin hasn't been successful. Do you have any suggestions on how I can achieve this alignment using CSS? This is the code snippet: <div class="navbar "> <div class="cont ...

The current context for type 'this' cannot be assigned to the method's 'this' of type '...'

Currently, I am in the process of defining type definitions (.d.ts) for a JavaScript library. In this specific library, one of the methods accepts an object of functions as input, internally utilizes Function.prototype.bind on each function, and then expos ...

What is the way to activate Dynamic ng-model from a controller?

I am implementing a loop in my HTML code where each iteration dynamically creates a model. Here is an example of how the loop looks: <tr ng-repeat="item in voucherItems"> <td><input type="text" ng-model="this['id-' + $index ...

assign a JSON key to a variable

Is there a way to use a variable as a JSON key in JavaScript? var chtid = "1234" firebase.database().ref().set ({chtid :"hi"}); In this case, chtid is the variable. I have attempted this method without success: var chtid = "1234" firebase.database().re ...

``How can one validate a radio button within a reducer by utilizing the event object that is passed into the reducer process

In my React app, I am using the following reducer: const initialState = { genderRadio : false, ageRadio : false } const reducer = (state = initialState, action) => { switch(action.type) { case "VALI_RADIO_INP": console. ...

Troubleshooting React's failure to start with node.js running behind an Nginx Reverse Proxy

This is my first attempt at setting up a Node.js server in production (other than one Meteor server), and I've run into a problem that I can't figure out on my own. I have built an application using React. Here is the server code: // Imports va ...

The Navbar's Toggle Icon Causes Automatic Window Resize

I implemented a mobile navigation bar using React and JS that slides in from the left when clicked. However, I encountered two issues: whenever I click on a menu button in the navbar or when my ad carousel moves, the window resizes for some reason. Additio ...

Send form with information dynamically added via AJAX in Laravel

Below is the segment of HTML I am working with: <div class="box-body" style="display:none;" id="claimFreightDetails"> <input type="text" disabled class="form-control" id="pulledProNumber" name="pulledProNumber"><br> ...

Encountering a browser error when trying to access a C# method via AJAX: Javascript

I'm having trouble connecting to my Webservice. I keep getting an error 404, even though everything seems like it should be working fine. The issue started when I moved the code from my *.cshtml file into a separate .js file. The Javascript file is l ...

Using JSON in Node.js

After recently diving into Node, I've been working on parsing JSON data from an API. While I have managed to access most of the JSON content, there are certain elements that seem to elude me. var request = require("request"); var url = 'https: ...

Retrieving various pieces of data in Express

After scouring through various websites, I am still unclear on how to extract multiple GET variables using Express. My goal is to send a request to a Node.JS Express server by pinging the URL with: file_get_contents('http://127.0.0.1:5012/variable1/v ...

Errors may occur when attempting to auto-refresh a page with a PHP-generated image using Ajax

When I include the image somepage.php in my code, it displays correctly. However, if I use Ajax to refresh the div containing somepage.php, the text becomes distorted. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

Can you explain the significance of this?

Some may find this question silly, but I'm curious about the meaning behind certain elements in an ASPX page. For example, when there is code like this: <%@ Page Title="[$TITLES_listevents{uneditable}]" Language="C#" MasterPageFile="~/sitebase ...