How to keep user's input printed? - javascript

I'm trying to add a comments from user, so I just tried to read the input and send it to print it , but the problem is that the printed input disappears as soon as I refresh the page or enter another input.
so I want to keep all user's appearing always even when refreshing the page or re-entering a new comment.
code :
<div>
<input type="text" name="comments" placeholder = "Your comment goes here .. " class = "sug-box" id = "UserComment">
<button class = "send-box" onclick="go()">Add</button><i class="fa fa-send-o"></i>
<p id = "t"></p>
</div>
<script>
function go(){
var x = document.getElementById("UserComment").value;
document.getElementById("t").innerHTML = x;
}
</script>

There are two ways to do this depending on what your use case is.
The first is to use localstorage, which is significantly easier than using a database but has some downsides. Localstorage could be used if the comments were personal (meaning nobody else sees them). The problem with this is that localstorage is insecure.
Localstorage is a set key/value pairs stored on the users machine until deleted.
This is how you use localstorage:
// Place something in localstorage:
window.localStorage.setItem('key', 'value')
//Get something from localstorage:
window.localStorage.getItem('key')
//Delete item from localstorage
window.localstorage.removeItem('key')
Your full application might look something like this:
Javascript:
document.getElementById('comment').innerHTML = window.localStorage.getItem('comment') || ''
HTML:
<!DOCTYPE html>
<html>
<head>
<title>*title here*</title>
</head>
<body>
<textarea placeholder="Type comment here" id="comment"></textarea>
<br/>
<button onmouseup="window.localStorage.setItem('comment',document.getElementById('comment').value)">Submit</button>
</body>
</html>
The second way to do this is to use a database.
There are many different ways to do this, but I would recommend using node.js + express for middleware and mongodb for your database.
Here are some links to get you started:
node.js
npm
express
mongodb
Let me know if I missed anything and/or misunderstood the question.

I think I have a solution that should work for you. I have renamed and refactored some of your code a little, feel free to change it back to the original version if you wish. For me, this was easier to read. I also put the JS in a separate file, but you could accomplish the same task using the script tag.
Here is a link to a JSFiddle that shows it in action JSFiddle User-Comments-App. The code in the fiddle has been modified to work on that site, don't pay attention to it, look at the example below! You can't do page refreshes on JSFiddle so I simulated it with a Refresh Page button and a little timer function that clears the list then repopulates it from local storage.
HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<!-- calls this function on refresh to pull any coments from local storage -->
<body onload="populateUL()">
<div>
<input type="text" name="comments" placeholder = "Your comment goes here .. " class = "sug-box" id = "UserComment">
<button class = "send-box" onclick="parseUserComment()">Add</button><i class="fa fa-send-o"></i>
<p id = "t"></p>
</div>
<div id="comment-container">
<ul>
<!-- <li> items will be inserted here -->
</ul>
</div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
JavaScript
var commentUL = document.getElementById('comment-container').firstElementChild;
var commentNumber = 0;
function parseUserComment() {
var userComment = document.getElementById("UserComment").value;
storeUserComment(userComment, commentNumber);
displayUserComment(userComment);
commentNumber++;
}
function displayUserComment(userComment) {
var li = document.createElement('li');
li.textContent = userComment;
commentUL.appendChild(li);
}
function storeUserComment(userComment, commentNumber) {
window.localStorage.setItem(`comment-${commentNumber}`, userComment);
}
function populateUL() {
if (window.localStorage.length > 0) {
var i;
for (i = 0; i < localStorage.length; i++) {
var userComment = window.localStorage.getItem(`comment-${i}`);
displayUserComment(userComment);
}
// we need to reset the counter to begin in the last element of the array when we refresh the page.
commentNumber = localStorage.length;
}
}
Here's a brief breakdown of what's going on, let me know if you have any questions or if something is unclear.
Code Explanation
When the user clicks the 'Add' button, the parseUserComment() function will run. This function takes care of storing the comment in local storage, and displaying the comment on the screen. You'll notice that we pass the work of displaying the comment and storing the comment on to helper functions storeUserComment() and displayUserComment(). The only thing that parseUserComment() actually does is get the user's comment and increment the counter commentNumber:
var commentNumber = 0;
function parseUserComment() {
var userComment = document.getElementById("UserComment").value;
storeUserComment(userComment, commentNumber);
displayUserComment(userComment);
commentNumber++;
}
So, we have the user's comment, and we pass along the userComment to the helper function storeUserComment, which is just a single function call that add's the comment to local storage, using a naming convention 'comment-{commentNumber}'. This would mean the first comment would be 'comment-0', the second 'comment-1'. We use the 0-based system like in arrays. Note the use of template literals to allow us to easily concatenate the commentNumber to the string:
function storeUserComment(userComment, commentNumber) {
window.localStorage.setItem(`comment-${commentNumber}`, userComment);
}
After we have stored the user comment, we want to display it. And this function will also be used to display the user comments on a page refresh. We simply create a new 'li' element, and then make that elements text content the userComment. We then add this element to the 'ul' that sit's inside the div.comment-container, which we selected at the beginning of the file, using the appendChild() method:
// at beginning of file
var commentUL = document.getElementById('comment-container').firstElementChild;
function displayUserComment(userComment) {
var li = document.createElement('li');
li.textContent = userComment;
commentUL.appendChild(li);
}
So that covers the parseUserComment() function and the helpers it calls. Next we need to see how to show the user's comments when the page refreshes. For this, we add an event listener to the 'body' element for the 'onload' event:
<body onload="populateUL()">
The populateUL() function will check to see if there are any items in local storage, and if so, it will loop through those items and call the displayUserComment() function for each item:
function populateUL() {
if (window.localStorage.length > 0) {
var i;
for (i = 0; i < localStorage.length; i++) {
var userComment = window.localStorage.getItem(`comment-${i}`);
displayUserComment(userComment);
}
// bottom of function left off for clarity
At the end of the function, we have to be sure to set the commentNumber to the length of the localStorage array, which would be the last element. So, if you had two comments in localStorage, you would have 'comment-0' and 'comment-1'. The length of localStorage would be 2. We would print out 'comment-0' and 'comment-1' in the loop, then the 'i' variable would increment to 2, and the loop would stop. At this point, we can assign the length of localStorage to the commentNumber, so that if the user wanted to add a new comment, it would start numbering at 2 ('comment-2'):
commentNumber = localStorage.length;

Related

Javascript random that saves where the random has linked to already

So I tried writing this question before and it was closed. While I was still able to get comments, I am just assuming that I used up the amount of comments or something. Please, I just need to know how to call the javascript function in a link so that it works. Thank you to the person who provided the code for the function I just need to know how to call to it in a link. Nothing I have tried works. I have tried other javascript function searches and none of that works.
So I wrote a code for my job that is basically a quiz. It's HTML code. I wrote it so that it would be a set order for each question. Then I realized it'd be easy to memorize answers. I found a randomizer for links, but I need to know how to get it to remember which questions it's been to do they don't show up in the quiz again. Is this possible?
<html>
<head>
<title>
Easy Mode
</title>
<script src="https://randojs.com/1.0.0.js"></script>
</head>
<body align="center">
Welcome to Easy Mode<br>
In this mode, menu descriptions will be given <br>
after each image to make it easier to identify<br>
When you are ready, click the next button below <br>
Next
<script>
var allQuestions = ["question 1.html", "question 2.html", "question
3.html", "question 4.html"];
function getNextQuestion() {
var questions = JSON.parse(localStorage.getItem("questions"));
if (questions === null) questions = randoSequence(allQuestions);
if (questions.length == 0) return "VICTORY.html";
var question = questions.pop().value;
localStorage.setItem("questions", JSON.stringify(questions));
return question;
}
</script>
</body>
</html>
Thank you for all your help already given and any that will be given in the future
Have a look at this.
Uncomment the lines with localStorage when using (SO does not allow localStorage in snippets)
the script needs to be in each page
I suggest you ajax the question in, instead.
Anyway: working example
const allQuestions = ["question_1.html", "question_2.html", "question_3.html", "question_4.html"];
let storedQuestions;
// storedQuestions = localStorage.getItem("questions");
let questions = storedQuestions ? JSON.parse(storedQuestions) : allQuestions;
function getNextQuestion() {
let href = questions.length === 0 ? "VICTORY.html" : questions.splice(Math.floor(Math.random()*questions.length),1);
// localStorage.setItem("questions", JSON.stringify(questions));
alert(href+"\n"+questions); // remove when happy
return href;
}
Welcome to Easy Mode<br> In this mode, menu descriptions will be given <br> after each image to make it easier to identify<br> When you are ready, click the next button below <br>
Next
NOTE You need to get rid of the localStorage item to be able to run the quiz again. In my victory.html I have a button with
<button type="button" onclick="localStorage.removeItem('questions'); location.replace('start.html')">reset</button>
To reset in the start page have this ONLY in the top of the script on the start page:
localStorage.removeItem('questions')

Get dynamically created names of dynamical links

I need to create a link for a set of documents. They are created dynamically, thus the names are also different, f.ex. Test, Test2, so one.
I need to show the link like "Document TestN", where links changed according to the current document. I can now create the links by a href="id" onklick=bla+bla+bla", but the name does not change. Instead of 'Dashboard' I need to get 'Dashboard of "ConcreteSite"', where I can get names by pageHeader:
document.getElementById("pageHeading").appendChild(pageHeading);
<script language="javascript" type="text/javascript">
var siteNameAsParam = window.location.search;
var scrt_var = siteNameAsParam.split("siteName=")[1];
</script>
<p>You are here: Dashboard </p>
Based on your code I think this is what you're after but more detail on what you're trying to do would be great.
<p>You are here: Dashboard </p>
<p>You are here: Dashboard </p>
<script>
document.addEventListener('DOMContentLoaded', function(event) {
var links = document.getElementsByTagName("a");
for (i = 0; i < links.length; i++) {
var siteNameAsParam = window.location.search;
var scrt_var = siteNameAsParam.split("siteName=")[1];
links[i].href = links[i].href + '?siteName=' + scrt_var;
links[i].innerText += ' fred';
}
}, false);
</script>
This does the following:
On page load gets all links on the page
loops through the links and grabs the query strings from the url
splits the query string on siteName
sets each link url to add the query string
updates the links text to append the query string (or undefined if it doesn't exist (see note below)
Note: your code implies you already have a query string in the url of siteName=SITENAMEHERE. Also, depending what you're trying to achieve, there are probably much better approaches. This I hope answers your current question but I think you should review how other achieve what you're after.
Update:
Here is a jsfiddle with a different working sample of what I think you might want. Hopefully it helps. there are comments in the fiddle. I think you want to try doing more when the link is created (set the event listener there, update the text as desired, etc.) instead of on the click event.

Targeting specific row/line of textarea and appending that row

I want to be able to click on a specific element, and have it send a value to a textarea. However, I want it to append to a specific row/line of the textarea.
What I am trying to build is very similar to what happens when you click the notes of the fret board on this site: http://www.guitartabcreator.com/version2/ In fact, i want it almost exactly the same as this.
But right now I am really just trying to see how I can target the specific row, as it seems doable based on this website.
Currently I am using javascript to send a value based on clicking a specific element.
Here is the js:
<script type="text/javascript">
function addNote0(text,element_id) {
document.getElementById(element_id).value += text;
}
</script>
This is the HTML that represents the clickable element:
<td> x </td>
This is the textarea:
<textarea rows="6" cols="24" id="tabText" name="text">-
-
-
-
-
-</textarea>
This works fine for sending the value. But it obviously just goes to the next available space. I am a total newb when it comes to javascript, so I am just not sure where to begin with trying to target a specific line.
What I have currently can be viewed here: http://aldentec.com/tab/
Working code:
After some help, here is the final code that made this work:
<script>
function addNote0(text,element_id) {
document.getElementById(element_id).value += text;
var tabTextRows = ['','','','','',''];
$('td').click(function(){
var fret = $(this).index() - 1;
var line = $(this).parent().index() -1;
updateNote(fret, line);
});
function updateNote(fret, line){
var i;
for(i=0;i<tabTextRows.length;i++){
if(i == line) tabTextRows[i]+='-'+fret+'-';
else tabTextRows[i]+='---';
$('#tabText').val(tabTextRows.join('\n'));
}
}}
window.onload = function() {
addNote0('', 'tabText');
};
</script>
Tried to solve this only in JS.
What I did here is use an array to model each row of the textfield (note the array length is 6).
Then I used a jQuery selector to trigger any time a <td> element is clicked which calculates the fret and string that was clicked relative to the HTML tree then calls the updateNote function. (If you change the table, the solution will probably break).
In the update note function, I iterate through the tabTextRows array, adding the appropriate note. Finally, I set the value of the <textarea> to the array joined by '\n' (newline char).
Works for me on the site you linked.
This solution is dependant on jQuery however, so make sure that's included.
Also you should consider using a monospaced font so the spacing doesn't get messed up.
var tabTextRows = ['','','','','',''];
$('td').click(function(){
var fret = $(this).index() - 1;
var line = $(this).parent().index() -1;
updateNote(fret, line);
});
function updateNote(fret, line){
var i;
for(i=0;i<tabTextRows.length;i++){
if(i == line) tabTextRows[i]+='-'+fret+'-';
else tabTextRows[i]+='---';
$('#tabText').val(tabTextRows.join('\n'));
}
}
I wrote the guitartabcreator website. Jacob Mattison is correct - I am using the text area for display purposes. Managing the data occurs in the backend. After seeing your site, it looks like you've got the basics of my idea down.

How to add multiple jQuery populated HTML numbers together from different pages?

I'm a first time poster and I'm learning jQuery, so I'll try to formulate my words as best as possible.
On my site I have multiple pages that dynamically add up the lis and gives me a number.
That number is displayed this way: var totalOverallString = $("#overallTotal").html(total);
Currently I have two similar variables in two functions.
Everything is working correctly on the individual pages.
Now I want to take those two numbers, add them, and display that new number in my home page.
I want this to work dynamically like in my other pages.
The problem I run into is getting those numbers from the other pages.
I've tried .load and .getScript to extract the numbers. I've also tried doing a callback function, but the script loads and gives me the original declared variable: total = 0. This makes sense to me. It's not adding up the lis from the original page. Both variables are global.
I'm trying my best to wrap my head around how to do this. How do I get that dynamically added .html(total) from the other page?
Thanks for your time!
This is the only way I can think to do it without storing all the list items in a database or similar.
Example page 1 containing some list items, here called list-1.html:
<html>
<body>
<ul>
<li>One</li>
<li>Two</li>
</ul>
</body>
</html>
Example page 2 containing some list items, here called list-2.html:
<html>
<body>
<ul>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>
</body>
</html>
Example page where you want the count of list items to be displayed, in this case, your homepage:
<html>
<body>
<!-- Element to contain the total -->
<p>Total list items: <span id="count">counting...</span></p>
<!-- Include jQuery -->
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
(function() {
// Update this array of URLs to the pages containing <li>s that you want to count.
var urls = ["list-one.html", "list-two.html"];
var $hidden = $("<ul />").hide();
var total = 0;
// use jQuery's selective loading functionality to load LIs from each URL, count them, and add the count to a running total
for(var i = 0; i < urls.length; i++) {
$hidden.load(urls[i] + " li", function(responseText) {
total = total + $hidden.find("li").length;
// complete - update the count element.
if(i == urls.length) {
$("#count").html(total);
}
});
}
})();
</script>
</body>
</html>
So essentially we are requesting each page containing list items to count, counting all list items on those pages and keeping a running total.
N.B. depending on the number of pages and lists you need to count, this may not be particularly efficient. But it will work, and I think is the only realistic way you can achieve this without using a DB or complex scraping/caching systems.
you can store your individual values into localStorage or sessionStorage which availlbe with HTML5
There are two new objects for storing data on the client:
localStorage - stores data with no expiration date
sessionStorage - stores data for one session
you can use localStorage or sessionStorage is client side cookies to store your individual value, then you are going to show your total into different page retrieve the value from localStorage and show it :)
Again if you dont want to cache total values set expire time of localStorage 0 which will be expired when browser closed.
for more details on localStorage http://www.w3schools.com/html/html5_webstorage.asp

Javascript Validation of dynamic textarea

Hi I'm using a CMS which dynamically creates textareas on product pages of an ecommerce site. The text area has a different ID on each different product page. I am in need of some javascript that will check if all textareas on a page are empty and if so display a warning message. I cant assign an id to the text areas so cant use this script I normally use. Any help is much appreciated!
function validate() {
var val = document.getElementById('textarea').value;
if (/^\s*$/g.test(val)) {
alert('Wrong content!');
}
}
Hey Benjamin thanks for your reply, I couldn't get the code working in comments, thinking I'm having a bad day. So as i was trying to say I'm not the greatest at Javascript (but eager to learn!) I've added this to my page but it doesn't appear to work:
<script>
var areas = document.getElementsByTagName("textarea");
// now iterate them for
(var i=0;i<areas.length;i++){
var val = areas[i].value;
if (/^\s*$/g.test(val)) {
// whatever
}
} </script>
With this as in the body
<div class="description">Further Details <br>
<textarea id="catProdInstructions_6486638" class="productTextarea"></textarea>
</div>
Thanks for your time on this :)
You can use getElementsByTagName to fetch all <textarea>s.
It returns a NodeList of all the text areas currently in the page which you can iterate.
var areas = document.getElementsByTagName("textarea");
// now iterate them
for(var i=0;i<areas.length;i++){
var val = areas[i].value;
if (/^\s*$/g.test(val)) {
// whatever
}
}
The NodeList returned is live , this means that it'll update itself automatically as new textarea elements are added dynamically even if you fetch them with ajax or create them with code.

Categories

Resources