Reputation: 1532
I have a button in the main page which on clicking opens a modal. I have a form in the modal with a button which, on submitting closes the modal and returns to the main page. I want to change the html button which is on the main page after closing the modal to plain text. How would I replace the main button in main page after the modal is closed ?
function submitForm() {
alert('yes');
var button = document.getElementById('mainButton');
button.style.display = 'none';
}
<body>
<button id="mainButton"> Click here </button>
<div class="modal">
<form onsubmit="submitForm()">
<input type="text">
<button> Done </button>
</form>
</div>
</body>
I tried the following in submitForm function:
removing the button like this:
document.getElementById('mainButton').innerHTML = '';
Also tried: document.getElementById('mainButton').style.display = 'none'
Upvotes: 0
Views: 2205
Reputation: 65806
You are working with a submit
button (that's the default type of button you get with <button>
). So, when you click it, the onsubmit
event handler fires and the form submits, which results in the current page being unloaded, so trying to display anything else isn't going to work.
In this scenario, you'd need the form to redirect to another page that has the content you want on it (that is done by configuring the form
element's action
attribute.
If you don't really need to submit data to a server, then you can change the type of button you have to a regular button
and change the event handler to handle just a click
event and then just take what you are already doing to the next level.
In addition to hiding what you no longer want to see with display:none
, you can show something that is set up ahead of time and defaulted to display:none
and then change it to display:block
when it's time to show it.
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>
Upvotes: 1
Reputation:
You could do something like this to replace your button with a div containing its text.
var mainButton = document.getElementById('mainButton');
var buttonText = mainButton.textContent;
var newDiv = document.createElement('div');
newDiv.textContent = buttonText;
document.body.removeChild(mainButton);
document.body.appendChild(newDiv);
Upvotes: 0