Reputation:
I have a div box and it has some text in it. How can I change the text through user input ? I want that when a user click on the div box the input field should show up and then user can input some text and it should be updated.
<div class="update-card-body">
<p>I want to change this text.</p>
</div>
Upvotes: 1
Views: 100
Reputation: 78520
You could just use HTML5's contenteditable attribute.
document.querySelectorAll('[contenteditable=true][id]').forEach(function(el){
cardBodyData = JSON.parse(localStorage.getItem('card-body-data'));
el.addEventListener('input', function(){
cardBodyData[el.id] = this.innerHTML;
localStorage.setItem('card-body-data',JSON.stringify(cardBodyData));
});
if(cardBodyData && cardBodyData[el.id]) {
el.innerHTML = cardBodyData[el.id];
}
if(cardBodyData === null) cardBodyData = {};
});
<div id="001" class="update-card-body" contenteditable="true">
<p>I want to change this text.</p>
</div>
<div id="002" class="update-card-body" contenteditable="true">
<p>I want to change this text.</p>
</div>
SO prevents the use of localStorage
in the snippet editor. Here's a fiddle using localStorage
to save changes to the contenteditable div: https://jsfiddle.net/0rqhmmg3/
Upvotes: 1
Reputation: 40038
I believe the key part of your question is here: and it should be updated
I suspect you mean that you want the text typed by the user to be saved somehow.
You have two options: front-end (localstorage
) and back-end (PHP or ASP.Net
)
For localstorage, the code to save looks like this:
localStorage.setItem("cardbody", "This is what they typed");
and to retrieve it:
$('.update-card-body').text(localStorage.getItem("cardbody"));
For PHP, you can either use a <form>
or use AJAX:
References:
Note: PHP is very common - it comes with most shared hosting packages (GoDaddy, Hostgator, Namecheap, etc). If you wish to play with it on your local computer, install a free package called XAMPP - it has OSX, Windows and Linux distros. Note that files go into xampp/htdocs
, and you view the website by typing ONLY localhost
into the browser address bar.
Upvotes: 0
Reputation: 11600
var displayBox = document.querySelector('.update-card-body>p');
var input = document.querySelector('.get-text');
input.addEventListener('keyup', function() {
displayBox.textContent = input.value;
});
<input class="get-text">
<div class="update-card-body">
<p>I want to change this text.</p>
</div>
Upvotes: 1