Home > Back-end >  Is there a script to replace a button with another button when clicked?
Is there a script to replace a button with another button when clicked?

Time:01-22

I have a form on my website, and an 'Edit' button, which allows the form to be edited via some javascript.

Then I have a submit button labeled 'Save Changes' which submits the form.

The additional script, which I posted below... does allow the 'Save Changes' button to appear, only after the 'Edit' button is clicked, and that's OK.

But, I would rather the 'Save Changes' button replace the 'Edit' button (in the same spot), after the Edit button is clicked.

Is there a simple script solution for this?

This is the working script I am currently using to make the 'Save Changes' (submit) button appear when the edit button is clicked.

SCRIPT:

document.querySelector('.saveChanges_Button').style.display = 'none'; 
document.querySelector('.editBtn').addEventListener('click', showBtn); 

function showBtn(e) { 
document.querySelector('.saveChanges_Button').style.display = 'block'; 
e.preventDefault(); 

}

CodePudding user response:

You can do the same thing you already do when clicking the Edit button.

If you click edit, then the edit button disappears and the save button takes it's place; vice-versa for the save button.

To have it be placed in the same spot as the other button, you can place them both in the same div.
Since display = 'none' means the element just doesn't exist on the page at that moment, the other item will take it's position on the page.

Edit: I added an example.

const editButton = document.querySelector('.editBtn');
const saveChangeButton = document.querySelector('.saveChanges_Button');

editButton.addEventListener('click', () => {
    saveChangeButton.style.display = 'block';
    editButton.style.display = 'none';
});
saveChangeButton.addEventListener('click', () => {
    saveChangeButton.style.display = 'none';
    editButton.style.display = 'block';
});
.editBtn {
    display: block;
    width: 15px;
    height: 15px;
    background-color: blue;
}

.saveChanges_Button {
    display: none;
    width: 15px;
    height: 15px;
    background-color: red;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div>
        <button ></button>
        <button ></button>
    </div>
</body>

</html>

  • Related