I have this code:
<script type="text/javascript">
function showTotal(form, totalEl)
{
var el, els = form.elements;
var sum = 0;
for (var i=0, num=els.length; i<num; ++i){
el = els[i];
if ('text' == el.type){ //&& /SumB/.test(el.name)
sum += +el.value;
}
form.elements[totalEl].value = sum;
}
}
</script>
If I use an alert I get the correct output but it fills the wrong value into "totalEl" You can test this on (fixed) It's the first block of checkboxes and textboxes!
Does it work if you try
<script type="text/javascript">
function showTotal(form, totalEl)
{
var el, els = form.elements;
var sum = 0;
for (var i=0, num=els.length; i<num; ++i){
el = els[i];
// Do not include totalEl
if ('text' == el.type && el != form.elements[totalEl]) {
sum += +el.value;
}
}
form.elements[totalEl].value = sum;
}
</script>
If totalEl is an element of the form, then the form.elements[totalEl].value = sum; line must be outside the for loop, otherwise the value of totalEl itself will be included in the last calculation, resulting in a double sum.
It'll add the value in the "sum" text element as well the way it's written right now. Use a class, or subtract the current total from the new total after adding, or just zero the element out before the loop.
As the other answer mentions, the part that sets the "sum" field shouldn't be in the loop, too.
Related
I want to enter five numbers into the array using one text box. And find the max number print it when I click the result button. I want to enter a number one by one when I clicked the add button it automatically add one by one to the array. HTML with JavaScript
var input = document.getElementById('input').value;
function Add(numbers) {
numbers = [];
for(int x = 0; x < 5; x++) {
var numbers = input[x];
}
return numbers;
}
function findMax(arr) {
var max = arr[0];
for(var i = 0; i < arr.length; i ++) {
if(arr[i] > max) max = arr[i];
}
return max;
}
function Result() {
document.write(document.getElementById('demo').innerHTML = findMax(arr))
}
<p id = "demo">Print here the result</p>
<input type = "text"; id = "input">
<button onclick = "Add()">Add</button>
<button onclick = "Result()">Result</button>
To get all the 5 elements in an array using a single textbox, if they are seperated by single space do this:
var arr = input.split(' ');
This will create an array 'arr' with the numbers in it!
Actually there are many errors, that needs to be fixed, in the code you wrote:
You are declaring the numbersarray twice, inside your add function, while you should be declaring it only once globally outside of it.
You don't need a loop to add the input value into the array, just use .push().
You don't need to return the numbers array after adding an element.
Don't use document.write() to show the result, just use document.getElementById('demo').innerHTML = findMax(numbers).
Make sure to pass the right numbers array to your findMax()function, instead of arr in findMax(arr).
Demo:
This is a demo with these errors corrected.
var input = document.getElementById('input');
var numbers = [];
function Add() {
if (numbers.length < 5) {
numbers.push(+input.value);
input.value = "";
}
}
function findMax(arr) {
var max = arr[0];
for (var i = 1; i < arr.length; i++) {
if (arr[i] > max)
max = arr[i];
}
return max;
}
function Result() {
console.log(numbers);
document.getElementById('demo').innerHTML = findMax(numbers);
}
<p id="demo">Print here the result</p>
<input type="text" ; id="input">
<button onclick="Add()">Add</button>
<button onclick="Result()">Result</button>
You can try this code bellow :
<body>
<p id = "demo">Print here the result</p>
<input type = "text"; id = "input">
<button onclick = "Add()">Add</button>
<button onclick = "Result()">Result</button>
<script>
var numbers=[];
function Add() {
var input = document.getElementById('input').value;
if(input != ""){
numbers.push(parseFloat(input));
}
document.getElementById('input').value="";
console.log(numbers);
}
function Result() {
console.log(numbers);
document.getElementById('demo').innerHTML = Math.max.apply(null, numbers);;
}
</script>
</body>
I'm trying to get input box values and select box values to store it each one in array and do some calculation and I couldn't get a result here is my javascript code:-
$(window).on('pageinit', function() {
$(document).ready(function(){
$("#Scal").click(function() {
var x = parseFloat($('[name^="Sc"]').val()) || 0
var y = parseFloat($('[name^="Sgrade"]').val()) || 0
var sum1 = 0;
var sum2 = 0;
for(var i=0; i< x.length; i++) {
sum1 += x[i]*y[i];
sum2 += x[i];
}
var sum3 = sum1/sum2
var sum3 = sum3.toFixed(2)
$('#Sres').val(sum3)
});
});
});
You need to loop over the elements from which you're pulling the values. Your parseFloat approach isn't going to work.
Do something like this to get the sum of all Sc values:
$(document).ready(function () {
var sumSc = 0;
$("#Scal").click(function () {
//loop over the matching elements with jQuery each()
$('[name^="Sc"]').each(function () {
sumSc += +$(this).val(); //the extra "+" here coerces a Number value
});
console.log(sumSc); //this outputs your total in the console
});
});
You can apply that same approach to sum the other elements and do your calculations.
For a homework assignment, I have to make a web page that has a text area. The user inputs some text, hits the analyse button, and the output is supposed to be a list of the frequency of words of a given number of characters. For example, "one two three" would be two words of three characters and one word of five characters. The text area works fine, but I can"t seem to get the output to appear.
Here is the html:
<body>
<textarea id="text" rows="26" cols="80"></textarea>
<form>
<input type="button" id="analyse" value="Analyse Text">
</form>
<div id="output"></div>
</body>
The JavaScript file has 6 functions. The first function returns an array that stores the number of characters for each word in the input textarea:
function getWordInfo() {
var text = document.getElementById("text").value;
//the variable wordArray uses a regular expression to parse the input
var wordArray = text.split("/\w\w+/g");
var arrayLength = wordArray.length;
var charArray = [];
for (var i = 0; i < arrayLength; i++) {
var splitWord = wordArray[i].split("");
var wordLength = splitWord.length;
charArray.push(wordLength);
}
return charArray;
}
The second function is a simple object constructor that has a name property and a count property. The count property has a default value of 0.
function obCon(name,count) { //object constructor
this.name = name;
this.count = count;
count = typeof count !== "undefined" ? count : 0;
}
The third function returns an array that stores word objects. Each object has a name property and a count property. The name property is the number of characters in a word. The count property counts how many times an object with a given name property appears.
function arCon() { //array constructor
var charNum = getWordInfo();
var arrayLength = charNum.length;
var obArr = [];
for (var i = 0; i < arrayLength; i++) {
if (typeof obArr.indexOf( newOb.name === charNum[i] ) != "undefined" ) { // checks if the object needed exists
obArr.indexOf( newOb.name === charNum[i] ).count = obArr.indexOf( newOb.name === charNum[i] ).count + 1;
}else{
var newOb = new obCon(charNum[i]);
newOb.count = newOb.count + 1;
obArr.push(newOb);
}
}
return obArr;
}
The fourth function is a string formatter, meant format the objects from arCon into a single readable string, then store it in an array.
function formatter() {
var strAr = arCon();
var arrayLength = strAr.length;
var formatStr = [];
for (var i = 0; i < arrayLength; i++) {
var str = "Number of characters: " + strAr[i].name + ", Number of words with this length: " + strAr[i].count;
formatStr.push(str);
}
return formatStr;
}
The fifth function is called for an event handler, meant to handle the click of the analyse button. On click, it is meant to get the div tag, get the formatted array, then loop though each element in the array, where it creates a p element element, pulls the formatted string, sets the p element value to the formatted string, then appends the p element to the div tag.
function analyseButtonClick() {
var div = document.getElementById("output");
var str = formatter();
var arrayLength = str.length;
for (var i = 0; i < arrayLength; i++) {
var par = document.createElement("p");
var format = str[i];
par.value = format;
div.appendChild(par);
}
}
The sixth function is an init function that handles the button click.
function init() {
var button = document.getElementById("analyse");
button.onclick = analyseButtonClick;
}
window.onload = init;
I have run this though a validator, and it shows me that there are no syntax errors, so it must be a logic error. However, all the functions seem to do what they are supposed to do, so I am not sure where I went wrong.
edit1: ok, have replaced the third function with four new functions. a function that returns the highest number in the array returned by getWordInfo, a function that constructs objects with name properties from 2 up to that number, a function that update the count properties of the objects, and a function that removes unused objects. here they are:
function maxNum() {
var array = getWordInfo();
var num = Math.max.apply(Math, array);
return num;
}
function objArrCon() { //object array constructor
var num = maxNum();
var array1 = [];
for (var i = 2; i === num; i++) {
var myObj = new objCon(i,0);
array1.push(myObj);
}
return array1;
}
function objArrParse() { //updates the object with word info
var array1 = getWordInfo();
var array2 = objArrCon();
var loopLength1 = array1.length;
var loopLength2 = array2.length;
for (var i = 0; i < loopLength1; i++) {
for (var m = 0; m < loopLength2; m++) {
if (array2[m].name === array1[i]) {
array2[m].count++;
}
}
}
return array2;
}
function objArrTrun() { //removes unused objects
var array1 = objArrParse();
var loopLength = array1.length;
for (var i = 0;i < loopLength; i++) {
if (array1[i].count === 0) {
array.splice(i, array1);
}
}
return array1;
}
still does not work, but im getting there!
I have written this in jQuery because 1) it's not my homework assignment and 2) it would be good practice (for you) to translate it back into normal JavaScript. You'll need to rewrite the event handler, along with the two getters/setters ($("text area").val() and $("tbody").append()).
Your main problem is that you have made your solution too complicated! If all you want to do is display the number, Y, of words with length, X, then you should do the following:
Grab the value of the text area and store in text
Remove all non-alphanumeric characters.
Split the text string wherever one or more spaces is present and store it in text
Loop through the array and map each array element, based on its length, to wordMap
Loop through wordMap and append it to wherever in the DOM you want the results to be
fiddle
JavaScript
$("#analyze").click(function () {
var text = $("textarea").val().replace(/[^\d\w ]+/g," ").split(/[ ]+/);
// this grabs the value of the text area, replaces all non-numerical
// and non-alphabetical characters with "", and then splits it into an array
// wherever one or more spaces is present.
var wordMap = {};
// makes an object that will be used as an associative array
text.forEach(function (d) {
// loops through the array
// if there is no key called d.length in wordMap
if (!wordMap[d.length])
wordMap[d.length] = 1; // set its count to one
else
wordMap[d.length]++; //otherwise, increment it
})
// loop through all the properties of wordMap
for (var x in wordMap) {
$("tbody").append("<tr><td>" + x + "</td><td>"
+ wordMap[x] + "</td></tr");
}
console.log(wordMap);
})
HTML
<textarea placeholder="type something..."></textarea>
<button id="analyze">Click to analyze</button>
<div id="results">
<table>
<thead>
<th>Length of Word</th>
<th>Number of Occurrences</th>
</thead>
<tbody>
</tbody>
</table>
</div>
I found the same examples over and over about how to sum values but I haven't been able to use it for myself. I have two sets of data saved in localStorage. The first values for both keys are numbers which I want to add together. I found many .each functions that do the looping but I want to do it while looking through the key/value pairs, have a variable contain the sum as the key/value pairs loop. So here's what I have:
$(document).ready(function(){
if(localStorage.length > 0){
for (var i=0, len=localStorage.length; i<len; i++){
var sum = 0;
var key = localStorage.key(i);
var val = localStorage.getItem(key);
var valu = val.split("*");
alert (valu[0]); //alerts twice 130 and 160
sum += valu[0]; //didn't do anything
sum += parseInt(valu[0]); //also didn't work
alert (sum);
}
}
});
So the two values are 130 and 160 and they alert out as the function loops...so how can I add them and have like a running total as it loops?
You need the var sum = 0; outside the loop, as follows:
$(document).ready(function(){
if(localStorage.length > 0){
var sum = 0;
for (var i=0, len=localStorage.length; i<len; i++){
var key = localStorage.key(i);
var val = localStorage.getItem(key);
var valu = val.split("*");
alert (valu[0]); //alerts twice 130 and 160
sum += parseInt(valu[0]); //also didn't work
alert (sum);
}
}
});
My application needs to retrieve all DOM elements in javascript and
and put there values into one variable
i.e
if my application is having three text boxes then i want there values in comma separated form in javascript variable
If you want all DOM elements, which you probably don't, but if you do...
document.getElementsByTagName('*');
What I think you want is something like this
var form = document.getElementById('my-form').
var inputs = form.getElementsByTagName('input');
var inputsCsv = [];
for (var i = 0, length = inputs.length; i < length; i++) {
if (inputs[i].type === 'text') {
inputsCsv.push(inputs[i].value);
}
}
inputsCsv = inputsCsv.join(',');
in below example i am taking values of all textboxes of a table. you can pass form name there.
var frm = document.getElementById('tblemail').getElementsByTagName("input");
var len = frm.length;
var myval='';
for (i=0;i< len;i++)
{
if (frm[i].type == "text")
{
if(myval =='')
{
myval = frm[i].value;
}else{
myval += ',' + frm[i].value;
}
}
}