I have <p>
a certain text</p>
I want by onClick to changes this into a <input value="certain text">
,
so it can be edited.
All the solutions I found were clicking on a button. I want the text hides and the input-field appears instead.
I have <p>
a certain text</p>
I want by onClick to changes this into a <input value="certain text">
,
so it can be edited.
All the solutions I found were clicking on a button. I want the text hides and the input-field appears instead.
function makeInput(e) {
e.innerHTML = '<input value="'+e.innerText+'">';
}
<p onclick="makeInput(this)">a certain value</p>
A possible alternative is to just make the content of the p tag editable and use javascript to submit the information without using a input tag.
<p contenteditable="true">This is an editable paragraph.</p>
Click to Edit, click away when done editing.
HTML:
<div class="editable">
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Nullam dapibus porttitor sem, et tristique neque vehicula eu.
Nulla porta ex semper sapien luctus bibendum. Donec et congue nisi
</div>
CSS:
textarea {
width: 100%;
max-width: 400px;
padding: 10px 20px;
min-height: 120px
}
JS:
var eventHandler = function(e){e.preventDefault(); editDiv(this);};
document.querySelector('.editable').addEventListener("click", eventHandler);
function editDiv(div){
var text = div.innerText,
textarea = document.createElement("TEXTAREA");
textarea.value = text;
div.innerHTML = "";
div.append(textarea);
textarea.focus();
textarea.addEventListener("focusout", function(e){
finishEditDiv(div);
});
div.removeEventListener("click", eventHandler);
}
function finishEditDiv(div){
//handle your data saving here
var text = div.querySelector('textarea').value;
div.innerHTML = text;
document.querySelector('.editable').addEventListener("click", eventHandler);
}
Assign the onClick
to the p tag.
Create an hidden input.
On click hide the current p, and get the input associated to that p, then display it.
function onClick(e) {
e.currentTarget.style.display = 'none';
document.querySelector('#p-input').style.display = 'block';
}
<section>
<p onClick="onClick(event)">Clickable text</p>
<input id="p-input" style="display:none;" type="text" />
</section>
You may use input element only. Use a disabled input with a styling of your choice ( grayish background for example ). Use onClick event to set the input to active and change its style ( no background ).
Worked pretty good for me.
tags and add it as the initial value of the input, or just want to have an input tag with an empty string as the initial value?
– Ray Chan Jan 01 '19 at 17:47itself?
– Tony Thomas Jan 01 '19 at 17:51