I am trying to create a form with variable fields.
Start with plain text, and when someone clicks on that text, it goes into an editable text input field. When someone clicks, he returns to the edited text.
I let him go, but it doesn't seem to be working properly. Works great on the first two clicks, but then it loses the inputId and mixes the buttons.
Here is the html
<p id="firstElement" onclick="turnTextIntoInputField('firstElement');">First Element</p> <p id="secondElement" onclick="turnTextIntoInputField('secondElement');">Second Element</p>
And here is the JavaScript (using jQuery).
I am completely new in JavaScript, so it may not be the best quality code ...
function turnTextIntoInputField(inputId) { console.log(inputId); inputIdWithHash = "#"+inputId; elementValue = $(inputIdWithHash).text(); $(inputIdWithHash).replaceWith('<input name="test" id="'+inputId+'" type="text" value="'+elementValue+'">'); $(document).click(function(event) { if(!$(event.target).closest(inputIdWithHash).length) { $(inputIdWithHash).replaceWith('<p id="'+inputId+'" onclick="turnTextIntoInputField(\''+inputId+'\')">'+elementValue+'</p>'); } }); }
Here is a live example on the fiddle https://jsfiddle.net/7jz510hg/
I will be grateful for any help as this gives me a headache ...
zachu source share