Let us assume, I have a <div> element and I want to make this element editable. Why would you do this to a <div> element (or any element) when you can use a textbox? Well, I guess, you should see this post to understand why.
Ok, now check this out.
<div id='theText' contentEditable> </div>
The property contentEditable takes a Boolean true or false as a value. You can define it the way I have shown it in the above markup or set the value true or false explicitly. For example,
<div id='theText' contentEditable='true'> </div>
Now, let’s see how we can set the property value to true (or false) dynamically using jQuery.
jQuery provide two separate methods to get or set the properties of an element dynamically. The methods are .attr() and .prop(). I’ll use these two methods here.
jQuery Script using .attr() Method
<body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id='theText'></div> </body> <script> $(document).ready(function () { $(function () { $('#theText') .attr('contenteditable', 'true'); }); }); </script>
Using the .attr() method, I have just set the contentEditable’s property to true. Now you can enter some values in the <div>, just as you enter values in a textbox.
👉 Note: The property is case-sensitive. See how it is defined in-line (that is in the mark section within the element) and how it defined inside the .attr() method.
Although, this 👉 .attr('contentEditable', 'true'); works. However, it should be .attr('contenteditable', 'true');
Now, using .prop() Method
You can also use the .prop() method in jQuery to set the contentEditable property to either true or false.
In this example, the <div> is editable. However, I'll set the value to false using the .prop() method.
Note: The .prop() method was introduced in jQuery 1.6.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id='theText' contentEditable> </div> $(document).ready(function() { $(function() { $('#theText').prop('contenteditable', 'false'); // or assign value “true”. }); });
Well, I have used two different methods to perform a particular task, which is to set the contentEditabe property to true (or false) using a script in jQuery. Although, the header of this article says, how to set the value as true, the 2nd example sets the contentEditabe’s value to false. It can work either ways. Both the examples are useful.
Don’t want to use a library to do this! No problem. You can keep this simple using plain old JavaScript.
document.getElementById('theText').contentEditable = 'true';
Its just a one-line code to set the property as true or false.
👉 Do you know you can convert your browser into a Notepad? O yes you can. See this demo.