Javascript - localStorage issues - javascript

In the script below, I want to be able to display on the main html page lists of paragraphs saved in the localstorage. In the html I defined an are with the id "content". I want to display the texte stored in the localstorage in this area.
In the script below the function "displaylocalstorage" does not allow me to display the values that have been saved in the localstorage with the function "storedparagraphs". Can you please give me some guidelines to correct the "displaylocalstorage" function? Is my while loop correct ? Is the way I call the fucntion "display locastorage" is correct ?
Here is the html and js script below:
Javascript:
const mybutton = document.getElementById ("addbutton");
const mytext = document.getElementById("mytext");
const content = document.getElementById("content");
function displaylocalstorage() {
let n = 0;
while (localStorage.getItem("content" + n)) {
n++;
}
while (n){
const paragraph = document.createElement("p");
paragraph.innerText = localStorage.getItem("content");
content.appendChild(paragraph);
n++
}
}
}
displaylocalstorage()

displaylocalstorage is not being called.
add this to your js
const buttonshow = document.getElementById("buttonshow");
buttonshow.addEventListener("click", displaylocalstorage);
and to your html:
<input
type="button"
value="show"
id="buttonshow"
class="buttonshowall"
/>
and console log items in the displaylocalstorage
Thank would be a good start. Other than this in that paragraph remove length from n as n is a number. If you keep it as length it will error.
if(n>0){
let lastposition = n -1;
localStorage.removeItem("content", lastposition)
}
Another big one is change const n to let as you try to update n and const won't allow you to do that.

Related

Alert showing when it shouldnt be (XML Parse)

<script>
async function loadData() {
var data = await fetch("Product.xml");
var parsedData = await data.text();
var parser = new DOMParser();
var Product_document = parser.parseFromString(parsedData,"text/xml");
var results = "";
var AlertBox = ""
var user_id_input = document.getElementById("user_id").value;
var todos = Product_document.getElementsByTagName("product");
for(var i = 0; i < todos.length; i++) {
var Name = todos[i].getElementsByTagName("Name")[0].childNodes[0].nodeValue;
var Code = todos[i].getElementsByTagName("Code")[0].childNodes[0].nodeValue;
var Quantity = todos[i].getElementsByTagName("Quantity")[0].childNodes[0].nodeValue;
var Description = todos[i].getElementsByTagName("Description")[0].childNodes[0].nodeValue;
var Price = todos[i].getElementsByTagName("Price")[0].childNodes[0].nodeValue;
if(user_id_input === Code) {
results = "<div>"
+ "Code: " + Code
+ ",<br/> Name: " + Name
+ ", <br/>Quantity: " + Quantity
+ ",<br/> Description " + Description
+ ",<br/> Price " + Price
+ "</div><br/>";
AlertBox= "True";
}
if(AlertBox !== "True") {
alert("Error");
}
}
document.getElementById("results").innerHTML = results;
}
</script>
I'm trying to code a web app that takes user input, parses an XML file and then displays some information. I have that part working.
My problem is, I want there to be an Error alert if the Input does not match any of the XML elements. I have coded one in, but for every element the app checks that doesn't match the user input the app is giving me an error alert. And I have no idea how to solve it.
enter image description here
I've tried adding a variable that changes to true if the input matches and only allowing the alert to show up if that variable is false and I still get the Alert.
enter image description here
Based on your code I think the reason why it is not working is the nodeValue property as this returns null.
When called on an element tag (nodeType 1) nodeValue returns null. nodeValue will return the actual text content when it is called from a text element (nodeType 3). The 'Code' tag is of type element and has a child of type text therefore you don't get the desired text value. You can read more on nodeType here.
To get the correct result from nodeValue you need to call it like this:
var Name = todos[i].getElementsByTagName("Name")[0].childNodes[0].firstChild.nodeValue;.
As you want to get the text content from an element you can also use the following code instead:
var Name = todos[i].getElementsByTagName("Name")[0].childNodes[0].textContent;
The if condition should now also be executed correctly as long as the user_id_input variable has also the correct value. If the function loadData is executed before the user has entered values into the form fields, you need to execute the function when your form has been submitted. This way you can make sure that the user has entered values to all required fields. You can read more about HTML Forms and managing them via JavaScript here if needed.
I would also suggest to use let and const instead of var.
Additionally I think you would like to use your variable AlertBox as a boolean. If that is the case please use the boolean datatype in JavaScript. You can write it like this:
let AlertBox = false; or let AlertBox = true;

Calculating two variables that hold input data and outputting it

I think this is a simple fix but I cannot for the life of me seem to think about why this isn't working.
I'm a complete novice at JavaScript and HTML as you can probably tell by the code below but I just want it to be functional so I can learn by it.
The goal is to take two of the input values (what the user puts into those boxes specifically) and then divide and multiply that value with a specific integer that doesn't change and output the result into a paragraph.
function calculateValues(){
let pretext = document.getElementById("preresults");
let userinput = document.getElementById("results");
let userdistanceboxinput = document.getElementById("distancebox").innerText;
let userfuelboxinput = document.getElementById("fuelinputbox").innerText;
let oneimperialgallontolitre = 4.546;
let oneimperialgallontous = 1.201;
userinput.style.visibility = 'visible';
pretext.style.visibility = 'visible';
userinput = (userdistanceboxinput / userfuelboxinput) * 4.544;
The function is tied to an onclick event on a submit button as follows:
<button type="submit" id="submitbutton" onclick="calculateValues()" value="Submit">Submit</button>
Any help with this would be appreciated.
To get a value in Javascript, you can do this:
<input type="number" id="input1">
const input1 = document.getElementById('input1'); // retrieve the HtmlInputElement
const value1 = input1.target.value; // retrieve the value of this element
If you want to set a HtmlInputElement value you can do (same html):
const input1 = document.getElementById('input1'); // retrieve the HtmlInputElement
input.target.value = value1 * 21545 // set value of HtmlInputElement

Take variable values and put them in another file

I'm coding the game blockly, I have a variable called lineCount which counts the number of line breaks. however this variable is in a file called lib-dialog.js. When I insert the value of this variable with innerHTML I can get the value of lines by creating a div in the soy.js file (File by which I need to treat the result) But I need this value in a variable to put an if(lines == 6) { }
// Add the user's code.
if (BlocklyGames.workspace) {
var linesText = document.getElementById('dialogLinesText');
linesText.textContent = '';
// Line produces warning when compiling Puzzle since there is no JavaScript
// generator. But this function is never called in Puzzle, so no matter.
var code = Blockly.JavaScript.workspaceToCode(BlocklyGames.workspace);
code = BlocklyInterface.stripCode(code);
var noComments = code.replace(/\/\/[^\n]*/g, ''); // Inline comments.
noComments = noComments.replace(/\/\*.*\*\//g, ''); /* Block comments. */
noComments = noComments.replace(/[ \t]+\n/g, '\n'); // Trailing spaces.
noComments = noComments.replace(/\n+/g, '\n'); // Blank lines.
noComments = noComments.trim();
var lineCount = noComments.split('\n').length;
var pre = document.getElementById('containerCode');
pre.textContent = code;
if (typeof prettyPrintOne == 'function') {
code = pre.innerHTML;
code = prettyPrintOne(code, 'js');
pre.innerHTML = code;
}
if (lineCount == 1) {
var text = BlocklyGames.getMsg('Games_linesOfCode1');
} else {
var text = BlocklyGames.getMsg('Games_linesOfCode2')
.replace('%1', String(lineCount));
}
linesText.appendChild(document.createTextNode(text));
document.getElementById("contarBloco").innerHTML = lineCount;
var contandoBloco = lineCount;
}
I need to take the variable lineCount and put its value in another js.but I'm only managing to insert it into a div with innerHTML
it is better you use localstorage . Set the value of localcount in the local storage and get wherever you want
var lineCount = noComments.split('\n').length;
localStorage.setItem("lineCount", lineCount); // in first file
var count = localStorage.getItem("lineCount") // in second file
with this logic you will get the value but it will be string then for that you either use directly string or convert into integer using parseInt method
parseInt(count);
may be it will help . Thanks
I don't know if your Javascript files are modules, if so, you can return a function in your lib-dialog.js page and return it.
Example
lib-dialog.js =
let Dialog = (function() {
function SetLineCountVariable(LocalLineCount){
LineCount = LocalLineCount;
}
return SetLineCountVariable
})();
And in your soy.js file
let Soy = (function() {
Dialog.SetLineCountVariable(6);
})();
And do not forgot to call your JS file in order in your HTML page
Another way, if you only want the variable result in your another JS file, in your lib-dialog.js, show the result of LineCount in html tag and get it in your another JS file with document.getElementById

Javascripts calculates total based on form selections

I have an html form that I want to use javascript to calculate the total based on values of the form selection.
I was able to get my code work, but after trying to save it to JS fiddle it doesn't seem to be calculating anymore. Is there something in my code that is causing the error?
Here is the link to my full code:
https://jsfiddle.net/kmurray13/gc02Lsmh/
Here is just my javascript:
function calculatePrice(){
//Get selected data
var elt = document.getElementById("Quantity");
var quantity = elt.options[elt.selectedIndex].value;
var elt = document.getElementById("size");
var size = elt.options[elt.selectedIndex].value;
var elt = document.getElementById("page_count");
var page_count = elt.options[elt.selectedIndex].value;
var elt = document.getElementById("cover_stock");
var cover_stock = elt.options[elt.selectedIndex].value;
var elt = document.getElementById("text_stock");
var text_stock = elt.options[elt.selectedIndex].value;
//convert data to integers or decimals
quantity = parseInt(quantity);
size = parseFloat(size);
page_count = parseInt(page_count);
cover_stock = parseFloat(cover_stock);
text_stock = parseFloat(text_stock);
//calculate total value
var total = ((cover_stock * quantity)) + ((text_stock * page_count) * quantity);
//print value to PicExtPrice
document.getElementById("PicExtPrice").value=total;
}
My goal is to get the calculation when you click the 'Calculate Price' button, but I am not sure what I have done to the code to cause this error.
No it's not anything in your code that's causing the issue. It's because you were loading the javascript in the onload event thus the calculatePrice function wasn't present in the DOM thus you were getting the error. Fixed here: https://jsfiddle.net/fm3g64x0/
This is because jsFiddle is configured by default to wrap your JS code in onload event handler. If you look in your console you are getting a ReferenceError for calculatePrice() because it is out of scope.
In the Javascript jsFiddle pane, click where it says JavaScript + No-Library (pure JS) and where it says Load Type select No wrap - bottom of and rerun your code.

How can I get my input value from input field in a div using JavaScript

I am trying to get the value from an input field and display it using a div tag, but it's not displaying anything. Where am I wrong?
var num = document.getElementById("inputNum").value;
var numbersList = document.getElementById('numbers').innerHTML = num;
<input type="text" id="inputNum">
<div id="numbers">
</div>
Here is the code,
HTML
<input type="text" id="inputNum">
<div id = "numbers">
</div>
Javascript
var num = document.getElementById("inputNum");
var numbersList = document.getElementById('numbers');
num.onkeyup= function(e){
numbersList.innerHTML = e.target.value;
}
keyup will detect every key that is being typed and it will display to the div
Use a onkeyup event. This will give you ever character from text box. After getting the value you can easily set it using innerHTML. Consider the following snippet:
<script>
function setValue(){
var num = document.getElementById("inputNum").value;
document.getElementById('numbers').innerHTML = num;
}
</script>
<input type = "text" id ="inputNum" onkeyup="setValue()">
<div id = "numbers">
In var numbersList = document.getElementById('numbers').innerHTML = num; just omit var numbersList =. Code document.getElementById('numbers').innerHTML = num; will set innerHTML of Element with Id = "numbers" and will not return anything.
Your code will be:
var num = document.getElementById("inputNum").value;
document.getElementById('numbers').innerHTML = num;
or just
document.getElementById('numbers').innerHTML = document.getElementById("inputNum").value;
You have a few problems, and your needs aren't totally clear, but hopefully this will help. Here are the things I fixed:
This line
var numbersList = document.getElementById('numbers').innerHTML = num;
contains an error because it has two equals signs. I replaced it with two lines, first identifying the element and saving it to the variable numbersList, then setting the innerHTML property of numbersList to the num discovered above.
Secondly, the javascript you've written will presumably run once, when the page is loaded. At that time the input contains no text, so there's nothing to copy to the div. Depending on what you're trying to do, there are a few ways to handle this, but as one example, I've put the code you wrote (with the above fix) into a function, then added a button and assigned the function to run when the button is clicked.
Please let me know if you have any questions.
function copyVal() {
var num = document.getElementById("inputNum").value;
var numbersList = document.getElementById('numbers')
numbersList.innerHTML = num;
}
document.getElementById('copy').onclick = copyVal;
<input type = "text" id ="inputNum">
<div id = "numbers"></div>
<button id="copy">copy text</button>
So a few things is happening below.
First, we ensure that the whole page is loaded. Why? If your script is loaded at the beginning, it may have troubles accessing the DOMs (input, textarea, div, etc). Of course, if you load the Javascript at the botton of your page, you can skip such issue.
However, I decided to implement the (function() {...}); self-execute function. This will ensure your Javascript runs after the page its loaded.
Then, I added an event listener to the DOM object of inputNum. This listener will keep an eye to keyup events of your keyword. Each time a key goes up, after being pressed, it will run the code inside the function.
// This function will execute when the whole page is loaded
// This means that all the DOMs (such as your input and div) will be available
(function() {
var inputNum = document.getElementById("inputNum");
inputNum.addEventListener("keyup", function(){
var num = inputNum.value;
document.getElementById('numbers').innerHTML = num;
});
})();
<input type = "text" id ="inputNum">
<div id = "numbers"></div>
Note: I could have use the attribute keyup='' in the input field; however, I decided to give you an answer that provides 100% control. In this way, you can decide which type of event is more appropriate to the project you are working with.
var num = document.getElementById("inputNum");
var numbersList = document.getElementById('numbers');
num.addEventListener('change', function(){
numbersList.textContent = this.value;
})
Try this:
var num = document.getElementById("inputNum").value;
document.getElementById('numbers').innerHTML = num;

Categories

Resources