How to Disable Readonly Attribute on Textbox with jQuery

Last updated 1 month ago | 69 views 75     5

Tags:- HTML JQuery CSS

Introduction

Creating input text fields dynamically can be useful for forms that require variable input fields, such as adding multiple entries without refreshing the page. This guide demonstrates how to achieve this using JavaScript and jQuery.

✅ Step 1: Set Up the Basic HTML Structure

Create a container for the input fields and a button to add new inputs.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic Input Fields</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>

<h2>Dynamic Input Fields</h2>
<div id="inputContainer">
    <input type="text" name="inputField[]" placeholder="Enter text" readonly>
</div>
<button id="addInput">Add Input</button>
<button id="enableInput">Enable Input</button>

</body>
</html>

✅ Step 2: Add JavaScript for Dynamic Input Creation

$(document).ready(function() {
    $('#addInput').click(function() {
        $('#inputContainer').append('<input type="text" name="inputField[]" placeholder="Enter text" readonly>');
    });

    $('#enableInput').click(function() {
        $('#inputContainer input').removeAttr('readonly');
    });
});

✅ Step 3: Optional - Remove Input Fields

If you want to remove input fields, you can modify the script as follows:

$(document).ready(function() {
    $('#addInput').click(function() {
        $('#inputContainer').append('<div class="input-group"><input type="text" name="inputField[]" placeholder="Enter text" readonly><button class="removeInput">Remove</button></div>');
    });

    $(document).on('click', '.removeInput', function() {
        $(this).parent().remove();
    });

    $('#enableInput').click(function() {
        $('#inputContainer input').removeAttr('readonly');
    });
});

✅ Step 4: Styling (Optional)

Add some CSS for better user experience.

.input-group {
    margin-bottom: 10px;
}
.removeInput {
    margin-left: 10px;
}

Conclusion

By using jQuery, you can easily create input text fields dynamically and control their editability. This approach is beneficial for forms with variable input needs and enhances the user experience.