I am using contenteditable="true" in a div
What I want to do it to toggle true and false on this attribute everytime I click on a div.
example:
$( "#mylabel" ).click(function() {
$('#editablediv').attr('contenteditable','false');
});
I tried:
$( "#mylabel" ).toggle(function() {
$('#editablediv').attr('contenteditable','false');
});
but that didn't work
How can I do this?
I am using contenteditable="true" in a div
What I want to do it to toggle true and false on this attribute everytime I click on a div.
example:
$( "#mylabel" ).click(function() {
$('#editablediv').attr('contenteditable','false');
});
I tried:
$( "#mylabel" ).toggle(function() {
$('#editablediv').attr('contenteditable','false');
});
but that didn't work
How can I do this?
Share Improve this question asked Apr 19, 2014 at 14:00 Satch3000Satch3000 49.4k89 gold badges224 silver badges349 bronze badges 3- possible duplicate of How to Make HTML Content Editable with JavaScript / jQuery? – bobthedeveloper Commented Apr 19, 2014 at 14:02
- It works ,try jsfiddle.net/jxfxM/1 – Pratik Joshi Commented Apr 19, 2014 at 14:02
- FYI ... The example on possible duplicate is not correct as that example toggles a class ... I need to toggle an attrible so it's not a duplicate. – Satch3000 Commented Apr 19, 2014 at 14:09
5 Answers
Reset to default 11Try this way:
$( "#mylabel" ).click(function() {
var value = $('#editablediv').attr('contenteditable');
if (value == 'false') {
$('#editablediv').attr('contenteditable','true');
}
else {
$('#editablediv').attr('contenteditable','false');
}
});
Keep me posted, hope this helped
Here is shorter than your shortest (Reusability and Character Count):
function editTheElement() {
var a = "contenteditable";
$(this).attr(a) === 'true' ? $(this).attr(a,'false') : $(this).attr(a, 'true');
}
or still
function editTheElement(e) {
var a = "contenteditable";
e.attr(a) === 'true' ? e.attr(a,'false') : e.attr(a, 'true');
}
or
function editTheElement(e) {
var a = 'contenteditable';
var v= e.attr(a);
e.attr(a,!v);
}
or
function editTheElement(e) {
var a = 'contenteditable';
e.attr(a,!e.attr(a));
}
or
function editTheElement(e) {
e.attr('contenteditable',!e.attr('contenteditable'));
}
JS is fun :)
In 2018 at least, most of these answers aren't working past the first on/off in Chrome 68. It's something with how jQuery or the browser is reading the value of this attribute, because the logic is pretty simple.
The code I found to work was
var el = $("{your selector}")
(el.attr('contenteditable') ?
el.removeAttr('contenteditable') :
el.attr('contenteditable', true));
Demo Fiddle
shortest solution I found:
$('[contenteditable]').attr('contenteditable') === 'true' ?
$('[contenteditable]').attr('contenteditable', 'false') :
$('[contenteditable]').attr('contenteditable', 'true');
$('#mylabel').click(function() {
editable = $('#editablediv').attr('contenteditable');
$('#editablediv').attr('contenteditable', !(editable == 'true'));
});