I need to toggle between input and text on click. Something like live edit.
I wrote this code, but it doesn't work.
HTML:
<span class="editInput">Change the value on click</span>
<button>Click me</button>
JS:
var editmode = false;
$('button').on('click',function(){
if(editmode){
$('.editInput').replaceWith(function(){
return '<span class='+this.className+'>'+this.value+'</span>';
editmode = false;
})
}else {
$('.editInput').replaceWith(function(){
return '<input type="text" value='+this.text+' class='+this.className+'/>';
editmode = true;
})
}
})
Can someone help me?
Check out this Fiddle. It's not very elegant, but I think it's a quick, cleaner solution than what you were doing. Let me know if you have any more questions.
First,
this.text
should bethis.innerText
or$(this).text()
.Second, you need quotes around the
value
attribute in the<input>
tag, or it won't work with multiple words in the value. It would be even better to use the object form of the jQuery element constructor, so that quotes in the value don't cause a problem, either.Third, the assignment to
editmode
needs to be outside thereplaceWith
function. It's after thereturn
statement, so it's never being executed.Final result:
var editmode = false;
FIDDLE