Manoz
Manoz

Reputation: 6587

Editable textbox in jQuery

I am working on Asp.net MVC4 application. I have user's information and edit button in case any user wants to edit his/her information.

A user can edit his/her information by double clicking on it also. Suppose if a username is there then user can edit it by clicking double on it. As soon as he clicks on UserName it is editable with its value in a textbox.

How can i make value editable with textbox?

I tried-

$(function(){
    $('.double').on('dblclick',function(){
        var val=$(this).html();
        $(this).append('<input type="text" value=val/>');
    });
});

But no success.

Fiddle

Upvotes: 1

Views: 4290

Answers (4)

Suresh Atta
Suresh Atta

Reputation: 121998

Try to use contentEditable attribute

$(".double").get(0).contentEditable = "true";

the contenteditable attribute is an enumerated attribute whose keywords are the empty string, true, and false. The empty string and the true keyword map to the true state. The false keyword maps to the false state. In addition, there is a third state, the inherit state, which is the missing value default (and the invalid value default).

DEMO1 | DEMO2

Upvotes: 3

Dhaval Marthak
Dhaval Marthak

Reputation: 17366

Try like this:

Use .replaceWith():

$(document).on('dblclick', '.double' function() {
    var val = $(this).text();
    $(this).replaceWith('<input type="text" value="' + val + '" class="username" />');
});

And to revert back to div:

$(document).on('blur', '.username', function() {
    var val = $(this).val();
    $(this).replaceWith('<div class="double">' + val + '</div>');
});

Demo

Upvotes: 1

asifrc
asifrc

Reputation: 5841

You just need to concatenate val properly:

$(this).append('<input type="text" value="'+val+'">');

http://jsfiddle.net/asifrc/wKAvs/3/

Upvotes: 0

Ephi Gabay
Ephi Gabay

Reputation: 938

$(function(){
    $('.double').on('dblclick',function(){
        var val=$(this).text();
        $(this).append('<input type="text" value=\"' + val + '\" />');
    });
});

Upvotes: 0

Related Questions