Swap out the HTML button element for text once the form is submitted

On the main page, I have a button that opens a modal when clicked. Inside the modal, there is a form with a submit button that closes the modal and returns to the main page. After closing the modal, I want to change the HTML button on the main page to plain text. How can I replace the main button on the main page once the modal is closed?

function handleSubmit() {
  alert('yes');
  var replacement = document.getElementById('mainButton');
  replacement.style.display = 'none';
}
<body>
  <button id="mainButton"> Click here </button>
  <div class="modal">
    <form onsubmit="handleSubmit()">
      <input type="text">
      <button> Done </button>
    </form>
  </div>
</body>

In my `handleSubmit` function, I attempted the following:

Removing the button using:

document.getElementById('mainButton').innerHTML = '';

I also tried: document.getElementById('mainButton').style.display = 'none'

Answer №1

When dealing with a submit button in your form, the default behavior is for the form to submit when clicked, causing the current page to unload. This prevents any further display modifications from taking effect.

To work around this limitation, consider redirecting the form to another page where you can set up the desired content by specifying the destination URL in the action attribute of the form element.


If submitting data to a server is not necessary, you can change the button type to a standard button and handle the click event instead of the submission event. This allows you to enhance the user experience without refreshing the page.

In addition to hiding elements using display:none, you can also reveal pre-configured content that is initially hidden by toggling its visibility from display:none to display:block at the appropriate time.

function submitForm() {
  alert('yes');
  var button = document.getElementById('mainButton');
  button.style.display = 'none';
  
  // Remove the class that hides the element that you want to now see
  document.querySelector(".afterClick").classList.remove("afterClick");
}
.afterClick { display:none; } /* Defaults to hidden */
<body>
  <button id="mainButton"> Click here </button>
  <div class="afterClick">Thanks!</div>
  <div class="modal">
    <form onclick="submitForm()">
      <input type="text">
       <button type="button"> Done </button>
    </form>
  </div>
</body>

Answer №2

If you want to swap out your button for a div that displays the same text, you can use this code snippet:

const originalButton = document.getElementById('originalButton');
const buttonText = originalButton.textContent;

const newDiv = document.createElement('div');
newDiv.textContent = buttonText;

document.body.removeChild(originalButton);
document.body.appendChild(newDiv);

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

Trouble with Selecting an un-ordered list menu item in Selenium Java's side bar navigation

Exploring a different approach to selecting a menu item in the sidebar navigation within an iframe. After switching to the iframe, I am attempting to choose a specific item from the side menu to display its respective navigational items for selection. Thes ...

Clearing existing HTML content in the TR body

I've been struggling with a Jquery/Ajax call that updates cart details. Currently, I can't seem to clear the existing HTML content in the cart-body (tablebody) even though the ajax request adds all the items to the cart successfully. The code sni ...

How can I select elements in CSS that are "between x and y"?

If I have an HTML table with 20 rows and 3 columns (20x3), I am looking to highlight the rows from 7 to 12 in red. What CSS selector should I use for this specific task? How can I define the range of rows to be styled as "between"? ...

Tips on updating arrow button icon when clicked using jquery

I am currently working on a project where I have a button icon that I want to change upon clicking it. I am using the following jQuery code: <script> $('div[id^="module-tab-"]').click(function(){ $(this).next('.hi').sl ...

"Optimizing the placement of a range slider for pricing options

As a beginner in HTML, CSS and JS, I recently faced the challenge of creating a price slider range on a website. However, I am struggling with repositioning it. After copying the code from this link, I noticed that the slider is positioned at the top of th ...

Customizing form designs with the combination of Django and Bootstrap

After developing a basic purchase form with custom fields, I conducted a test to ensure its functionality. The form rendered successfully, as shown below. <form id="category_form" method="post" action="/purchase/"> {% csrf_token %} { ...

Titanium: Picture -> "automatically"

Imagine there is an image named hello.png with the dimensions of 200x100. A button is then created using this hello.png as shown below: var btn = Titanium.UI.createButton({ bottom : 50, backgroundImage : "images/hello.png", width:100, height:"auto"; }); w ...

The presence of whitespace is causing disruptions in the text alignment within div elements

I've noticed some unwanted white space on my website when viewing it in Chrome and Internet Explorer. It's interrupting the flow of text and I can't figure out where it's coming from. Can someone help me locate and remove this pesky wh ...

Use the arrow key to move through the different layers

I'm working on enhancing a custom auto-complete feature using JQuery. My goal is to allow the user to navigate down into the auto-complete dropdown and then back up to the input box that triggered it initially. The code snippet below demonstrates how ...

Is it possible to have unique color tags in Material UI Autocomplete?

I'm currently diving into the world of material-ui and encountering some challenges that I could use help with. I am trying to incorporate multiple arrays into the autocomplete menu (e.g., options={top100Films, top100Shows}, but with the correct sy ...

``on click of the back button of the browser, automatically submit the form

I'm facing a specific issue that I need help with. I have created a form with a hidden value, and I want it to be submitted when the user clicks the browser's back button. Although I've managed to control the backspace key, I haven't be ...

Display or conceal numerous WTForm labels

Is there a more efficient way to hide/show multiple wtform labels? Currently, I am achieving this with the following code: HTML: {{ render_field(var_1, class = "class_1") }} {{ render_field(var_2, class = "class_1") }} {{ render_field(var_3, class = " ...

Shift the content downwards within an 'a' snippet located in the sidebar when it reaches the edge of the right border

I'm having an issue with my style.css file. As a beginner in programming, I am trying to position text next to an image attached in the sidebar. However, the text is overflowing past the border. Here's the HTML code: Please see this first to ide ...

Utilizing the 'PUT' update technique within $resource

Hey there, I'm pretty new to Angular and looking for some guidance on how to implement a PUT update using angular $resource. I've been able to figure it out for all 'jobs' and one 'job', but I could use some assistance with in ...

The application has encountered an unexpected error and is currently unavailable

This is the code snippet for my MainActivity.java file. I am developing a simple LoginApp. However, when I try to run the app, it displays an "unfortunately stopped working ERROR..." message. package com.example.loginapp; import android.os.Bundle; import ...

What is the best way to enable horizontal scrolling for textarea overflow in a smooth manner like input, without any sudden jumps?

Currently, I am interested in utilizing a one-line textarea (with rows=1 and overflow-x:hidden;) similar to input type="text. However, I have encountered an issue where the content scrolls with "jumps" while typing inside it: https://i.stack.imgur.com/Rzf ...

Ways to specify the default value for a component

A sample of my custom component code (Amount.tsx) is shown below: const Price = ({ price, prevPrice }) => { return ( <div className="product-amount"> <div className="price"> {prevPrice ? (<del class ...

Is it possible to share an .ics file using SparkPost in a Node.js environment?

Attempting to generate an i-cal event and link it to a sparkpost transmission in the following manner: const event = cal.createEvent({ start: req.body.a.start, end: req.body.a.end, summary: req.body.a.title, description: req.body.a.body, ...

Choose options from an array in AngularJS using the same ng-model for a dropdown menu

I have developed a cross-platform app using AngularJS, Monaca, and OnsenUI. Within the app, there is a large form with multiple drop-down select options. The majority of these options are Yes/No selections. To handle these Yes/No options, I've creat ...

Harness the power of electrons with the simple push of a button - initiating program execution

Recently, I delved into Electron with the desire to create a small application for myself. This app would allow me to run different programs or games by simply clicking on a link. My goal is to have the program/game start automatically when I open the Ele ...