Home > OS >  Remove 'readonly' attribute from multiple form fields with edit button
Remove 'readonly' attribute from multiple form fields with edit button

Time:01-19

I have a form on my website with multiple user data fields; 'name', 'phone', 'email'.

By default, I want the page to load with the fields set to 'readonly'.

Then, I want to be able to click an 'edit button' to remove the 'readonly' attribute from all of the fields, so they may each be edited if need be.

I am using this bit of javascript, which I can set to select the inputs by either the generic ('input'), by the id ('#any_shared_id'), or by the class ('.any_shared_class').

However, so far... no matter which selector I use, I can only get this script to effectively remove the 'readonly' attribute from the first input.

The Form:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Edit Test Form</title>
</head>
<body>

<button id="removeAttribute" name="editBtn">Edit</button><br><br>

<form action="" method="POST">

<label>Name:</label><br><input type="text" id="name"  name="name" 
value="John Smith" readonly><br><br>
    
<label>Phone:</label><br><input type="phone" id="phone"  name="phone" 
value="555-555-5555" readonly><br><br>
    
<label>Email:</label><br><input type="email" id="email"  name="email" 
value="[email protected]" readonly><br><br>

<button type="submit" name="submit">Submit</button>

</form>
</body>
</html>

The Script:

<script>

var editButton= document.querySelector('#removeAttribute');

var get= document.querySelector('#name');

editButton.addEventListener('click', () => {

get.removeAttribute('readonly');

});

</script>

CodePudding user response:

Your code is correct but it works only for the first input field.

Just use querySelectorAll, select all input fields, and remove the readonly attribute on all fields.

const elements = document.querySelectorAll("input");

elements.forEach(element => {
    element.removeAttribute("readonly");
});

const button = document.querySelector("#removeAttribute");
const elements = document.querySelectorAll("input");

button.addEventListener("click", () => {

    elements.forEach(element => {
        element.removeAttribute("readonly");
    });

});
<button id="removeAttribute" name="editBtn">Edit</button><br><br>

<form action="" method="POST">

<label>Name:</label><br><input type="text" id="name"  name="name" 
value="John Smith" readonly><br><br>
    
<label>Phone:</label><br><input type="phone" id="phone"  name="phone" 
value="555-555-5555" readonly><br><br>
    
<label>Email:</label><br><input type="email" id="email"  name="email" 
value="[email protected]" readonly><br><br>

<button type="submit" name="submit">Submit</button>

</form>

  • Related