What is the best way to use JavaScript to conceal a section of a form div?

After receiving some code from a certain platform and implementing it to hide part of my form div element, I noticed that the element hides and unhides quickly when running in a browser. This rapid hiding and showing behavior occurs when clicking on the button to hide it. How can I solve this issue?

The details about what steps I have taken so far are outlined below:

.hide{

  display: none !important;
  visibility: hidden !important; 
}

.show{

display: block;
visibility:visible;

}

<!-- begin snippet: js hide: false console: true babel: false -->
<html>
<head>
    <title>

    </title>

    <script src="jquery/jquery-3.4.1.min.js"></script>
    <script src="jquery/jquery-3.4.1.slim.min.js"></script>
     <link rel="stylesheet" href="test.css">

    <script>


        $(document).ready(function() {
          //console.log('hello');
       
          $("#btn").on("click", function(){
            $("#form1").addClass("hide");
          })

        });

        
         //document.getElementById("form1").style.visibility="hidden";
          //document.getElementById("form1").style.display="none";
          
      
        </script>
        


</head>
<body>
<form>

<div id= "form1" class="show">
<label>Name</label>

<input type="text"/>
</div>

<br> <br>

<div id="form2">
<label>Email</label>

<input type="text"/>

</div>


<button type="submit" id="btn">more</button>


</form>


</body>


</html>

Answer №1

Ensure the button type is set to type="button"

<button type="button" id="btn">more</button>

Answer №2

There are several ways to improve this code, but if you simply want it to function properly, consider moving your button outside of the form or update your event listener as shown below:

$("#btn").on("click", function(e){
  $("#form1").addClass("hide");
  e.preventDefault();
})

The issue is caused by the button submitting the form and resulting in a page refresh.

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 access nested objects in React Native?

Here is the JSON data I am working with: [ { id: 51, name: 'Boat Neck Blouse', image: { id: 669, date_created: '2018-08-27T10:05:39', date_created_gmt: '2018-08-27T10:05:39', date_modified ...

Can you explain the concepts of 'theme' and 'classes'?

Currently, I am working on a web application using React. I have chosen to incorporate the latest version of Material-UI for designing the user interface. During this process, I came across the demo examples provided by Material-UI (like ) In each demo ...

initiate changes to the application's style from a component nested within the app

I'm looking to update the background color of the entire page, including the app-nav-bar, when I'm inside a child component. When I navigate away from that component, I want the default style to be restored. Any suggestions on how to achieve this ...

Improving JavaScript event management efficiency through handling numerous asynchronous HTTP requests

Summary: In a SPA CMS project, multiple dynamic data sources are causing performance issues due to a large number of asynchronous HTTP calls required to display a table with extensive data. The challenge is to maintain good performance while handling the ...

D3 - Error: Unable to access property 'text' of an undefined method

I want to create a visual representation of significant events that have occurred in the United States over the past 30 years. Below is a snippet of code I am using for this project: var mevent = svg.append("text") .attr("class", "year event") .at ...

Can Vue.js automatically refresh the display when there are changes in a third-party JSON file?

I'm attempting to achieve a specific goal using Vue, but I'm uncertain if it's feasible given my current struggles in obtaining the desired outcome: An API endpoint returns an array containing multiple objects. While I am able to successfu ...

An express error caught off guard: Unexpected "write after end" issue detected

My current goal is to create a proxy for an api call from the client side through my server for a third party service. The main reasons for implementing this proxy are due to CORS issues and the need to include a secret key on the server side for added sec ...

Obtain an image from a different domain using an HTTP request in jQuery

I am attempting to retrieve an image from a different domain and have tried the following code snippet: var img = "http://cdn.sstatic.net/Sites/stackoverflow/img/sprites.svg?v=bc7c2f3904bf"; $http.jsonp(img).success(function() { con ...

The website's favicon is mysteriously absent, particularly noticeable when using Google Chrome on my WordPress site

I recently added a favicon to my wordpress website, but for some reason it's not appearing on Chrome. If anyone could lend me a hand, I would greatly appreciate it! Any assistance would be wonderful, thank you! ...

Is it possible that activating the alert() function within a Node.js script could cause the server to freeze completely?

Given that Node.js operates on a single thread, is there a risk of freezing the entire server by calling functions like alert(), which typically wait for user input? Does Node.js have mechanisms in place to prevent such issues? ...

The Bootstrap carousel spiraled into disarray

I am facing an issue with the basic bootstrap carousel. My goal is to make the slides move every four seconds. The current setup of the carousel code is as follows: $(document).ready(function() { fixCarousel(); }); function fixCarousel() { $('.c ...

There is no POST data present in the jquery ajax request

I have been attempting to send data back to a controller using ajax from a lightbox, but unfortunately, it is not working as expected. The issue arises when I select values from two populated select lists and click submit – an error message briefly appe ...

Choosing from a variety of tr elements

I'm working with a table in HTML that has about 100 rows. I would like to apply different colors to specific groups of rows, such as making rows 1-10 red and rows 20-40 blue. Using nth-child seems like an option, but it can get quite verbose if I nee ...

transforming a table into a stylized CSS design

Seeking assistance in converting a table into CSS as I am new to CSS: <table dir="ltr" width="500" border="0" align="center"> <caption><font face="Helvetica">Movies</font></caption> <colgroup width="50%" /> ...

Creating a 3-column div with varying sizes of text in another div at the center position

I am attempting to create a 3-column layout using only DIVs, but I am facing some challenges. If I were to use tables in the traditional HTML 4 way, I could achieve this: <div style="width:100%"> <table width="50%" align="center"> ...

Creating an array of objects by parsing JSON using the jQuery .each() method

I am attempting to generate an array of objects by parsing a JSON file. Here is the pertinent code: //president object constructor function president(a_presName, a_presDates, a_presNick, a_presImage) { this.presName=a_presName; this.presDates=a_pr ...

Is it possible to identify when someone is copying a URL in a web browser?

During a recent conversation with a taxi driver, I mentioned that I work as a programmer. He then proceeded to tell me about an unusual experience he had a few days ago. While trying to copy the URL from his browser's address bar, a message box popped ...

Aligned sections within a Susy layout

Although Susy is a powerful tool, I have noticed a potential weakness with it. For example, imagine having three floated block elements within a container named "blocks": The "block" element is assigned a "span(4 of 12)" <div class="blocks"> &l ...

Tips for optimizing node_module file size

Currently, I'm developing 2-3 react applications and noticed that every time I run npm install, it ends up downloading numerous dependencies into the cumbersome "node-modules" folder, totaling around 250-300mb in size! This large size makes it challen ...

What steps can I take to prevent duplicate random numbers from occurring in my selection?

For my application, I incorporate a datepicker from jQueryUI that requires unique IDs for each input element. To achieve this, I implement the following function: var x = 100; $("a").on("click", function(){ console.log(Math.floor(Math.random() * x)); ...