user3117575
user3117575

Reputation:

How to make an element's content editable with JavaScript (or jQuery)

How would I make it so the content of an element could be made editable through native JavaScript (DOM) and/or jQuery?

Upvotes: 25

Views: 65221

Answers (6)

Mamunur Rashid
Mamunur Rashid

Reputation: 1185

All we have to do is set the contenteditable attribute on nearly any HTML element to make it editable.

Here's a simple example which creates a element whose contents the user can edit.

<div contenteditable="true">
  This text can be edited by the user.
</div>

Upvotes: 0

nicael
nicael

Reputation: 341

JavaScript:

document.getElementById('elementId').contentEditable = 'true';

Upvotes: 33

semirturgay
semirturgay

Reputation: 4201

Or you can use this plugin which i have been with no problem any time. it is realy simple and easy to use.

Here an example:

Html:

 <div style="margin: 150px">
    <a href="#" id="username">awesome</a>
</div>

JS

 $('#username').editable({
        type: 'text',
        url: '/post',    
        pk: 1,    
        title: 'Enter username',
        ajaxOptions: {
            type: 'put'
        }        
    });

DEMO

Upvotes: 0

Jelle Kralt
Jelle Kralt

Reputation: 990

If you use jQuery to add the attribute to the element you should be able to switch between edit mode and 'normal' HTML mode. The contenteditable attribute is supported by all major browsers. Check out http://blog.whatwg.org/the-road-to-html-5-contenteditable for more information.

Upvotes: 0

charlietfl
charlietfl

Reputation: 171698

Solution to toggle editable on/off using a click handler:

$('button').click(function(){
    var $div=$('div'), isEditable=$div.is('.editable');
    $div.prop('contenteditable',!isEditable).toggleClass('editable')
})

DEMO

Upvotes: 30

valek
valek

Reputation: 1376

Look at this example i've made: http://jsfiddle.net/K6W7J/

JS:

$('button').click(function(){
    $('div').attr('contenteditable','true');
})

HTML:

<button>CLICK</button>
<div>YOUR CONTENT</div>

Upvotes: 14

Related Questions