Prevent the box from closing automatically after submitting a form using jQuery

Despite my efforts to keep a simple dialog box open after submitting a form, it continues to close. I tried using the preventDefault method in jQuery, but it didn't solve the issue.

Below is the code snippet:

$(document).ready(function(e) {
  $('#toggle').click(function(e) {
        $('#box').toggleClass('max');
        e.preventDefault();
    });
  $('#close').click(function(e) {
      /*  $('#box').remove();*/
    });
});

Even experimenting with stopPropagation() did not yield any results.

If anyone has any suggestions, please share!

Here's the HTML snippet:

<div id="box" class="min">

    <span id ="toggle" class="fa fa-window-restore">
        <b>Open Dialog</b>
    </span>

    <form action="/conversations/3/reply" accept-charset="UTF-8" method="post">
        <input name="utf8" type="hidden" value="&#x2713;" />
        <input type="hidden" name="authenticity_token" value="VgKXI1p4MumSlvZF51pbXYKMMRLFKs0Us4NUB2+O7VZalzk++QDNQ5SsQMzvt4HlgUnlMa3ux54IDc3R/tGZhA==" />
        <textarea name="body" id="body" cols="3" class="form-control" placeholder="Type something..." required="required"></textarea>
        <button name="button" type="submit" class="btn_green">Send Message</button>
    </form>

</div>

Answer â„–1

To avoid the page from refreshing when submitting a form, you must use the method preventDefault() on the form's submit event.

document.querySelector('form').addEventListener('submit', e => e.preventDefault());

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

How to easily remove margin in a Bootstrap alert component

I'm having difficulty removing margins within a bootstrap alert component and I can't figure out why! https://codepen.io/weellydooh/pen/MWKKoqg <div class="alert alert-primary" role="alert"> <p>A simple primary alert—check it ...

Instructions on how to insert a single parenthesis into a string using Angular or another JavaScript function

Currently, I am employing Angular JS to handle the creation of a series of SQL test scripts. A JSON file holds various test scenarios, each scenario encompassing a set of projects to be tested: $scope.tests = [ { "Date": "12/31/2017", "Project": ...

Ways to enlarge image size without compromising the image resolution?

My image is in PNG format or as a blob. It has dimensions of 800px by 600px. However, when I try to resize it using various canvas methods like the one mentioned in this Stack Overflow thread: Resize image, need a good library, it loses quality. I wou ...

Tips for transferring the ID from one element to another using JavaScript

I'm attempting to create a slideshow using icons all within one class. The "active" style class will have an ID and represent the current picture. By clicking either the left or right button, I aim to change the style of the active class. const l ...

Guide on adding an item to the end of an array with an arrow function

const appendElement = (item) => { return (list) => { }; }; Add a new item to the end of the list. Parameters item (any): The item to add. Output (Array) => Array: Generates a closure that duplicates the original list with the added ite ...

Creating dynamic radio buttons in AngularJS

How can I create dynamic radio buttons in angularjs, using mobile numbers from this json array? challengeSelectInfo: [ {"mob_0" : "xxxxx1211"}, {"mob_1" : "xxxxx1211"}, {"mob_2" : "xxxxx1211"} ] I attempted to use ng-repeat and loop through c ...

Strategies for dynamically altering Vue component props using JavaScript

for instance: <body> <div id="app"> <ro-weview id="wv" src="http://google.com"></ro-weview> </div> <script> (function () { Vue.component("ro-webview", { props: ["src"], template: ` <input type="t ...

The Drupal-7 website encountered an AJAX HTTP error: HTTP response code 200

Running a clean Drupal installation, I have encountered a minor issue while running a simple program. A popup appears on the browser displaying: An AJAX HTTP error occurred I haven't installed many modules, just views and ctools on top of the basi ...

Encountering an error when attempting to iterate over an undefined property using an API

I am trying to fetch all classes and their assignments from Google Classroom. I successfully used Google's example code for listing the classes, but had to write my own code for listing the assignments. While the code runs as expected and lists the as ...

Express router route encountered a 404 Error

The first API endpoint is functioning correctly, however when attempting to access the second route, I am encountering a 404 error. Upon sending a GET request to http://localhost:3000/api/posts/, the response received is as follows: { message: "TOD ...

Making the child element expand to the full width of its parent while maintaining an overflow-x:auto property

Is there a way to stretch a child div without specifying fixed widths? Even when trying to wrap items and child in one wrapper div, the child div always takes up 100% width. Not full horizontal width. Thank you. .parent { background: skyblue; widt ...

Calculate the number of input boxes that have been filled

<input type="number" name="day1"> <input type="number" name="day2"> <input type="number" name="day3> Can anyone help me figure out how to count the number of filled fields in this form? For example, if only day1 is filled, the count resu ...

Position the caret beneath the anchor text

<a href="#" class="dropdown-toggle" data-toggle="dropdown" style="text-decoration: none"> <span class="criteria">any</span> <span class="caret" style="margin-top:6px;"></span> </a> The code snippet above ...

Upon initial login, React fails to retrieve notes

I developed a note-taking React app using the MERN stack with React Router DOM v6. When I initially visit the website, I am directed to the login page as intended. However, upon logging in, the page refreshes but does not redirect to the home page. This is ...

Adjust the width of an anchor tag

I have been experimenting with different solutions and unfortunately, I have not been successful in resolving the issue at hand. While working on a WordPress website, I encountered some challenges. Despite having some knowledge in this area, I am struggli ...

Safari is capable of rendering Jquery, whereas Chrome seems to have trouble

The code I am using renders perfectly in Safari but not in Chrome. Despite checking the console in Chrome, no errors are showing up. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="ht ...

Adding a new column to a table that includes a span element within the td element

I am attempting to add a table column to a table row using the code below: var row2 = $("<tr class='header' />").attr("id", "SiteRow"); row2.append($("<td id='FirstRowSite'><span><img id='Plus' s ...

Trouble with Bootstrap Popover's visibility

My current setup involves a popover that is not initializing properly. The code I am using is shown below: HTML: <div data-toggle="popover" data-placement="bottom" data-content="xyz">...</div> JavaScript: $(function () { $('[data-t ...

Make sure to only update the state in useEffect after retrieving the data from the localStorage

Trying to troubleshoot the continuous looping and crashing issue in my app caused by passing variables in the dependency array of the useEffect hook. These variables are state variables from the context provider. The goal is to make the useEffect hook run ...

Why won't applying a binding style affect the appearance of my Vue component?

const EventLevelBoard = { name: "EventLevel", data: { levelStyle: { display: "block" }, levelStyleinner: [ { display: "block" }, { display: "block" }, { display: "block&qu ...