Question

How do I make a textbox read-only from a JavaScript function?

Answer and Explanation

To make a textbox read-only using a JavaScript function, you can modify the readonly property of the input element. Here's how you can achieve this:

1. HTML Setup:

- First, ensure you have a textbox (input element) in your HTML. Give it an ID so you can easily target it with JavaScript. For example:

<input type="text" id="myTextbox" value="This is editable">

2. JavaScript Function:

- Create a JavaScript function that will set the readonly property of the textbox to true. This will make the textbox read-only.

3. Example JavaScript Code:

function makeTextboxReadOnly() {
  const textbox = document.getElementById('myTextbox');
  if (textbox) {
    textbox.readOnly = true;
    console.log("Textbox is now read-only.");
  } else {
    console.log("Textbox not found.");
  }
}

4. Calling the Function:

- You can call this function when a specific event occurs, such as a button click, or when the page loads. For example, to call it on page load:

document.addEventListener('DOMContentLoaded', makeTextboxReadOnly);

5. Making it Editable Again:

- To make the textbox editable again, you can create another function that sets the readonly property to false:

function makeTextboxEditable() {
  const textbox = document.getElementById('myTextbox');
  if (textbox) {
    textbox.readOnly = false;
    console.log("Textbox is now editable.");
  } else {
    console.log("Textbox not found.");
  }
}

6. Complete Example:

<input type="text" id="myTextbox" value="This is editable">
<button onclick="makeTextboxReadOnly()">Make Read-Only</button>
<button onclick="makeTextboxEditable()">Make Editable</button>
<script>
  function makeTextboxReadOnly() {
    const textbox = document.getElementById('myTextbox');
    if (textbox) {
      textbox.readOnly = true;
      console.log("Textbox is now read-only.");
    } else {
      console.log("Textbox not found.");
    }
  }
  function makeTextboxEditable() {
    const textbox = document.getElementById('myTextbox');
    if (textbox) {
      textbox.readOnly = false;
      console.log("Textbox is now editable.");
    } else {
      console.log("Textbox not found.");
    }
  }
</script>

By using these functions, you can dynamically control the read-only state of your textbox using JavaScript.

More questions