rista404 rista404 - 12 days ago 5
HTML Question

Jquery: Toggle between input and text on click

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?

Answer

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.

<div>
    <input/>
    <span>test</span>
</div>
<button>Update</button>

span {
    display:none;
}

$('button').on('click',function(){
    if($("input").is(":visible")) {  
        $("input").hide();
        $("span").text(
            $("input").val()
        ).show();
        $("button").text("Edit");
    } else {
        $("span").hide();
        $("input").text(
            $("span").val()
        ).show();
        $("button").text("Update");
    }
});
Comments