MarkP
MarkP

Reputation: 2566

on the fly editing of elements

I'm trying to allow users to log into the site and when they click a specific element, that element will change to an input text field and then allow the user to type whatever they wish into there.

However, once I click the inout field it keeps adding more code for another input field. Does this make sense?

Here is my jQuery:

$('.editTagline').click(function() {
  var content = $(this).html();
  $(this).html('<input type="text" value="' +content+ '">');    
});

Here is the JSFiddle: http://jsfiddle.net/nSY4Y/ if you click the word tagline and then try to enter text into the input text field you will see the problem.

Upvotes: 0

Views: 43

Answers (3)

Maurice Perry
Maurice Perry

Reputation: 32831

I would remove the class once the content is replaced:

$(document).on("click", ".editTagline", function() {
  var content = $(this).html();
  $(this).html('<input type="text" value="">');
  $(this).find("input").val(content);
  $(this).removeClass("editTagline");
});

fiddle

Upvotes: 1

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

You can use off:

$('.editTagline').on('click', function () {
    var content = $(this).html();
    $(this).html('<input type="text" value="' + content + '">');
    $(this).off('click');
});

demo

Upvotes: 1

adeneo
adeneo

Reputation: 318182

You can use one(), that way it only works once for each element

$('.editTagline').one('click', function () {
    var content = $(this).html();
    $(this).html('<input type="text" value="' + content + '">');
});

FIDDLE

Upvotes: 1

Related Questions