JavaScript - Adding text box values an storing it in an array - javascript

i need some code corrected. So here is the JS:
var $ = function (id) {
return document.getElementById(id);
}
var myTransaction = new Array[];
function processInfo() {
var myItem = $('item').value;
var myAmount = parseFloat($('amount').value);
var myTotal = myItem + ":" + myAmount;
var myParagraph = $('message');
myParagraph.innerHTML = myTransaction;
for (var theTotal in myTransaction) {
myTransaction += addTogether[theTotal] + "<br>";
}
}
window.onload = function () {
$("addbutton").onclick = processInfo;
}
and HTML
<section>
<p>Item:
<input type="text" id="item" size="30">
<p>Amount:
<input type="text" id="amount" size="30">
<p><span id="message">*</span>
<p>
<input type="button" id="addbutton" value="Add Item" onClick="processInfo();">
</section>
What i need to do is get the values of the text boxes, and add them together into one variable then have it stored into the array. Then use a for-in loop to concatenate every element in the Array into a one String variable. However, must also stick a tag at the end every value in the String, last thing is place this String in a paragraph at the end of the page.
FIDDLE

If I understand you then look at my edition to your code:
If you not understand something with the code so ask me.
At first you forget to close with ; the function $.
then you create array with bad syntax.
third you call addTogether array that doesn't exist.
this is fixed code that i belive working like you asked.
var $ = function(id) {
return document.getElementById(id);
};
var myTransaction = [];
function processInfo ()
{
var myItem = $('item').value;
var myAmount = parseFloat($('amount').value);
var myTotal = myItem + ":" + myAmount;
var myParagraph = $('message');
myParagraph.innerHTML = "";
myTransaction.push(myTotal);
for (var theTotal in myTransaction)
{
myParagraph.innerHTML += myTransaction[theTotal] + "<br>";
}
};
(function () {
$("addbutton").onclick = processInfo;
})();
Edit
Mohamed-Ted suggest:
instead of:
for (var theTotal in myTransaction)
{
myParagraph.innerHTML += myTransaction[theTotal] + "<br>";
}
you can do this:
myParagraph.innerHTML += myTransaction.join("<br>");
see example on:
jsFiddle

Related

js function doesn't work with JSON.parse

whats wrong with this code? when i click on button it shows undefined before first array value:
function loadDoc() {
var x;
var edare = JSON.parse('{"names":["ali", "mansour", "taghi"]}');
for (var i in edare.names) {
x += edare.names[i] + "<br>";
document.getElementById("demo").innerHTML = x;
}
}
<input type="button" onclick="loadDoc();" value="test">
<p id="demo"></p>
Because your x variable's initial value is undefined. So when you try to concatenate with another string it does undefined + string.
To fix this, you should give an initialize value to your variable:
var x = "";
Also, you should use for loops instead of for...in for arrays. Take a look at this for more information.
And finally, should also move your .innerHTML = x; outside of the loop to prevent updating the DOM on every iteration.
var x = "";
var edare = JSON.parse('{"names":["ali", "mansour", "taghi"]}');
for (var i=0; i<edare.names.length; i++) {
x += edare.names[i] + "<br>";
}
document.getElementById("demo").innerHTML = x;
Use .reduce() to construct a single string from the array of strings.
That way you only need to set the .innerHTML once.
function loadDoc() {
const edare = JSON.parse('{"names":["ali", "mansour", "taghi"]}');
document.getElementById("demo").innerHTML = edare.names.reduce((s, itm) =>
s + itm + "<br>"
, "")
}
<input type="button" onclick="loadDoc();" value="test">
<p id="demo"></p>
Or just .join() the list.
function loadDoc() {
const edare = JSON.parse('{"names":["ali", "mansour", "taghi"]}');
document.getElementById("demo").innerHTML = edare.names.join("<br>");
}
<input type="button" onclick="loadDoc();" value="test">
<p id="demo"></p>
Only difference here is that there's no trailing <br> at the end, but you can easily add that in if you really want it.
but it works with this:
function loadDoc() {
var x="";
var edare = JSON.parse ('{"names":["ali", "mansour", "taghi"]}');
for (var i in edare.names) {
x += edare.names[i] + "<br>";
document.getElementById("demo").innerHTML = x;
}
}
Iterate your array properly:
var i, nameConcat = "";
for(i=0; i < edare.names.length; i++){
nameConcat += edare.names[i] + "<br>";
}
document.getElementById("demo").innerHTML = nameConcat;
Or:
var concatNames = "";
edare.names.forEach(function(name){
nameConcat += name + "<br>";
});
document.getElementById("demo").innerHTML = nameConcat;

Form value always read as undefined in Javascript

I'm a new self taught programmer working on my first homework assignment, so I apologize if my naming convention is off. This is the most bizarre thing. No matter how I request the input value, (hoping to pull a number) it always reads as undefined.
Everything works in my javascript function except pulling the input value. I have used forms in the past, and the variables appear to be referencing it fine; I have tried both document.formName.inputName.value, as well as document.getElementById ('input-id').value and it returns undefined. I have renamed my form and variables so many times to see if that was the issue and stI'll nothing. I have tried both input type text and number, and stI'll undefined.
Am I missing something due to how new I am? Please help. Links to github and jsfiddle below.
https://github.com/MissElle/calculator?files=1
https://jsfiddle.net/MissElle/qf7xL8gj/
var dataInput = document.compute.calculate.value;
var element = Number(dataInput);
var numCount = document.getElementById('count');
var numSum = document.getElementById('sum');
var numMean = document.getElementById('mean');
var subCount = [];
var subSum = 0;
var starColors = ['#51fffc', '#ffff96', '#96ffc7', '#f8d8ff', '#d2bfff', '#ffbfbf', '#ffd299', '#ffffff', '#000000'];
function calcData(element) {
if(typeof element === 'number') {
console.log(element);
subCount.push(element);
var starDiv = document.createElement('div');
starDiv.className = 'star';
var starHolder = document.getElementById('star-holder');
starHolder.appendChild(starDiv);
starDiv.style.background = 'radial-gradient(circle, ' + starColors[Math.floor(Math.random() * starColors.length)] + ', transparent, transparent)';
numCount.innerHTML = subCount.length;
for(var i in subCount) {
subSum += subCount[i];
numSum.innerHTML = subSum;
var subMean = subSum/subCount.length;
numMean.innerHTML = subMean;
}
}else {
numCount.innerHTML = 'Not a Number';
console.log(element);
}
subSum = 0;
event.preventDefault();
}
function clearData() {
subCount = [];
subSum = 0;
subMean = 0;
numSum.innerHTML = '';
numMean.innerHTML = '';
numCount.innerHTML = '';
var starHolder = document.getElementById('star-holder');
var starDiv = starHolder.getElementsByClassName('star');
while(starDiv.length > 0) {
starHolder.removeChild(starDiv[0]);
}
}
<form name="compute" onsubmit="calcData()" onReset="clearData()">
<p class="bold">Please enter a number</p>
<input type="number" name="calculate" id="calculation" step="any"><br>
<input type="submit" name="submit" value="star">
<input type="reset" value="nostar" name="clearForm">
<div class="row">
<div class="typevalue"><h4>Count:</h4><h4>Sum:</h4><h4>Mean:</h4></div>
<div class="numbervalue"><p id="count"></p><p id="sum"></p><p id="mean"></p></div>
</div>
</form>
Move your variable declarations inside your function like this:
function calcData(element) {
var dataInput = document.compute.calculate.value;
var element = Number(dataInput);
var numCount = document.getElementById('count');
var numSum = document.getElementById('sum');
var numMean = document.getElementById('mean');
var subCount = [];
var subSum = 0;
var starColors = ['#51fffc', '#ffff96', '#96ffc7', '#f8d8ff', '#d2bfff',
'#ffbfbf', '#ffd299', '#ffffff', '#000000'];
...
If you declare your dataInput outside the function you get no value because that JS code is run after the page loads (before your user types any number in your function).
You have to declare it inside your function that way you get the value of your input when the user clicks on the button.

Javascript Higher Order Functions and DOM

I am working on a project that takes text that a user inputs in a text box and returns the most common word.
Javascript:
var bestMode = 1;
var currentMode = 0;
var character;
function Find_Word(){
var words = document.getElementById('words').innerText;
var punctuationless = words.replace(/['!"#$%&\\'()\*+,\-\.\/:;<=>?#\[\\\]\^_`{|}~']/g,"");
var finalString = punctuationless.replace(/\s{2,}/g," ");
var WordList = finalString.split(" ");
return FindMode(WordList);
}
function FindMode(WordList){
for(var i=0; i<WordList.length; i++){
for(var m=i; m<WordList.length; m++){
if(WordList[i] == WordList[m]){
currentMode += 1;
}
if(bestMode<currentMode){
bestMode = currentMode;
character = WordList[i];
}
}
currentMode = 0;
}
}
console.log(bestMode);
HTML:
<html>
<body>
<h1>Most common word used</h1>
<input type="text" id="words" rows="10" columns="30"></input>
<button type="button" id="FindWord" onclick="Find_Word()">Find Word</button>
<script src="CommonWord.js"> </script>
</body>
</html>
What I can't figure out is the correct way to pull text from the text box into a variable as one string. My function Find_Word takes the received string when the button is pressed and strips away punctuation and leaves an array WordList with with each individual word in the string.
After that, I also can't understand how to pass that array into my second function findMode where I iterate through each value of the array to find the most common word. That is saved in the variable bestMode.
It looks as if you are both getting the current text and passing the array correctly (although perhaps you should get the textbox value using the .value property). What problem are you having exactly? I am not sure what FindMode is supposed to do either.
Here is some script that is based on what you posted that sorts "words" according to how often they appear :
(function(w) {
w.Sort_Words = function(words) {
var o = {}, l = [];
for(var i=0; i<words.length; i++) {
if (typeof o[words[i]] === 'undefined') {
o[words[i]] = 0;
l.push(words[i]);
}
o[words[i]] ++;
}
l.sort(function(a, b) { return o[b] - o[a]; });
return l;
};
w.Find_Word = function() {
var text = document.getElementById('words').value;
var words = text.replace(/['!"#$%&\\'()\*+,\-\.\/:;<=>?#\[\\\]\^_`{|}~']/g,"").replace(/\s{2,}/g," ").split(' ');
var sorted = w.Sort_Words(words);
document.getElementById('results').innerText = sorted.length === 0 ?
'You must type at least one word' :
'The most commonly used word was: ' + sorted[0];
};
})(window);
Fiddler: http://jsfiddle.net/4u1mv20h/4/

Getting array from text

I have been experimenting with this code http://mounirmesselmeni.github.io/2012/11/20/javascript-csv/ to get data from a text file. (Working demo here: http://mounirmesselmeni.github.io/html-fileapi/).
It works well for reading files, but I am stumped about how to get the data into an array. It seems as though it is reading everything into the "lines" array, but I can't work out how to use it.
I tried modifying it like this:
function processData(csv) {
var allTextLines = csv.split(/\r\n|\n/);
var lines = [];
var myArray = [];
while (allTextLines.length) {
lines.push(allTextLines.shift().split(','));
myArray.push(allTextLines.shift().split(',')); //put data into myArray
}
function myFunction() { //display myArray in "demo"
var index;
for (index = 0; index < myArray.length; index++) {
text += myArray[index];
}
document.getElementById("demo").innerHTML = text;
}
but that didn't work. I know I am missing something simple here, but this has me stumped.
Currently you modify the array twice:
lines.push(allTextLines.shift().split(',')); // shift modifies the array
myArray.push(allTextLines.shift().split(',')); //gets the shifted array
You might want to try putting this in temp variable:
var line = allTextLines.shift().split(',');
lines.push(line);
myArray.push(line);
Try
csv.split(/\r\n|\n|,/).map(function(value, index) {
demo.innerHTML += "\n" + value.trim()
});
var csv = 'Year,Make,Model,Description,Price'
+ '1997,Ford,E350,"ac, abs, moon",3000.00'
+ '1999,Chevy,"Venture ""Extended Edition""","",4900.00'
+ '1999,Chevy,"Venture ""Extended Edition, Very Large""",,5000.00'
+ '1996,Jeep,Grand Cherokee,"MUST SELL!'
+ 'air, moon roof, loaded",4799.00',
demo = document.getElementById("demo");
csv.split(/\r\n|\n|,/).map(function(value, index) {
demo.innerHTML += "\n" + value.trim()
})
<div id="demo"></div>

appending values to textbox using for loop javascript

I am trying to add values to a textbox when looping through an array when checking checkboxes but as it is at the moment getting undefined.
Advice perhaps as to why the values are 'undefined'
var txtBoxValues = [];
$(document).on("click", "input[name=chkRelatedTopics]", function () {
var nameAdminUser = $(this).val();
var txtBox = document.getElementById("txtTraningTopics");
txtBox.value = '';
txtBoxValues.push(nameAdminUser);
for (var i in txtBoxValues) {
var str = txtBoxValues[i].value;
txtBox.value += str + '; ';
}
});
nameAdminUser is already a string, so don't take .value from it.
You could replace
var str = txtBoxValues[i].value;
with
var str = txtBoxValues[i];
But instead of using this loop, and assuming you don't want, as I suppose, the last ";", you could also do
txtBox.value = txtBoxValues.join(';');
nameAdminUser seems to be a String and in your for loop you expect an object. What if you simply do:
for (var i in txtBoxValues) {
var str = txtBoxValues[i];
txtBox.value += str + '; ';
}

Categories

Resources