Disable(readOnly) and Enable textbox using JavaScript

The following is a short example of a code that will enabledisable a textbox at the click of a button :

<html>

<script>

function enableDisable()

{

//This will get the HTML content of the current page

var form = document.testEnableDisable;

//The if condition checks for the value of the button.

if(form.enableDisableButton.value==”Disable”)
{

//If button value is ‘Disable’ then the textbox is made readOnly

form.textBox1.readOnly = true;

//The button value is changed to ‘Enable’

form.enableDisableButton.value=”Enable”

}

else

{

form.textBox1.readOnly = false;

form.enableDisableButton.value=”Disable”

}

}

</script>

<body>

<form name= “testEnableDisable”>

<input type = “text” id = “textBox1″ value=”Enabled”>

<input type=”button” id=”enableDisableButton” onClick=”enableDisable()” value=”Disable”>

</body>

</form>

</html>

Basically, its the readOnly value of the text box that needs to be changed using JavaScript.

Note: JavaScript is case sensitive and hence ‘readonly’ will not give you the right result…‘O’ should be in capital‘readOnly’ when you use it in JavaScript.

Click here to view the example

Leave a comment