2

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?

rista404
  • 7,639
  • 2
  • 18
  • 20

2 Answers2

2

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");
    }
});
beard
  • 91
  • 1
  • 2
  • 13
joshboley
  • 1,143
  • 6
  • 10
  • Thanks @joshboley! It works! And only one thing, it needs to show the span first, and then to show the input on click. I just hid the input in the css, and wrote the same value in the input. – rista404 Jun 24 '14 at 14:54
  • Yeah, that should work just fine. Glad I could help! – joshboley Jun 24 '14 at 15:32
0

First, this.text should be this.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 the replaceWith function. It's after the return statement, so it's never being executed.

Final result:

var editmode = false;

$('button').on('click', function () {
    if (editmode) {
        $('.editInput').replaceWith(function () {
            return $("<span>", {
                "class": this.className,
                text: this.value
            });
        });
        editmode = false;
    } else {
        $('.editInput').replaceWith(function () {
            return $("<input>", {
                value: this.innerText,
                    "class": this.className
            });
        });
        editmode = true;
    }

});

FIDDLE

Barmar
  • 741,623
  • 53
  • 500
  • 612