JavaScript forms and functions - javascript

I am trying to write a simple random number generator, where you input 3 integers into forms. The program then returns a certain amount of random numbers between the other two values. When I open the page the forms are displayed but when I click the button to generate the random numbers nothing happens. Why is this happening?
<html>
<head>
<script LANGUAGE="JavaScript">
function randomFromTo(from, to)
{
return Math.floor(Math.random() * ((to - from) + 1) + from);
}
function include(arr, obj)
{
for(var j = 0; j < arr.length; j++)
{
if (arr[j] == obj) return true;
}
}
function RandomGen(form)
{
var enteries = new Array();
var number = form.from.value;
var top = form.top.value;
var size = form.inputBox.value;
var count;
for (count = 0; count < size; count++)
{
var num = randomFromTo(number, top);
if (include(enteries, num) == true)
{
count--;
}
else
{
enteries[count] = num;
}
}
var i;
for(i = 0; i <= enteries.length; i++)
{
document.write(enteries[i]);
document.write("<br>");
}
}
</script>
</head>
<body>
<center><h1>Random Number Generator</h1></center>
<form name="myform" action="" method="GET">Enter the Range of Values
<input type="text" name = "from" value="">to
<input type="text" name = "top" value="">
<p>Enter The Amount of Random Numbers Needed
<input type="text" name = "inputBox" value=""><p>
<input type="button" name="button" value="Generate" onClick=RandomGen(this.form)">
</form>
</body>

You have a syntax error here
<input type="button" name="button" value="Generate" onClick=RandomGen(this.form)">
should be
<input type="button" name="button" value="Generate" onClick="RandomGen(this.form)">
Also this part should be updated, not because it will cause an error but because it is 2011
<script LANGUAGE="JavaScript">
should be
<script type="text/javascript">
Update
Or:
<script>
no need for the type attribute because it is 2018!

You missed a quote:
<input type="button" name="button" value="Generate" onClick="RandomGen(this.form)">

onclick="RandomGen(this.form)"
That part of your code was malformed. onclick is always all lower case and you were missing a "

Your missing a "
<input type="button" name="button" value="Generate" onClick="RandomGen(this.form)">

Related

Javascript form clears instantly and flashes one answer

I have an html page that uses a javascript as a statistical calculator, it just needs to print the results into the text boxes i have displayed, but when i hit my submit button, the screen displays the mean value for a split second. no other fields work or stay.
My html file is as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset=UTF-8>
<script src="script.js"></script>
<title>Script Calculator</title>
</head>
<body class="calculator">
<h2 class="stats">Statistical Calculator</h2>
<p> Enter 5-20 values within 0-100 inside the box below.<br>
Each value should be separated by one space.
</p>
<form>
<textarea id="numbers" name="numberarea" rows="4" cols="40"></textarea> <br>
<br>
<input type="submit" id="subbutton" onclick="performStatistics()"
value="Submit">
<input type="reset">
<br><br>
Max: <input type="text" id ="maxnum" name="max" readonly>
<br>
Min: <input type="text" id="minnum" name="min" readonly>
<br>
Mean: <input type="text" id="meannum" name="mean" readonly>
<br>
Median: <input type="text" id="mednum" name="med" readonly>
<br>
Mode: <input type="text" id="modenum" name="mode" readonly>
<br>
Standard Deviation: <input type="text" id="stddev" name="std" readonly>
<br>
Sum: <input type="text" id="sumnum" name="sum" readonly>
<br>
Variance: <input type="text" id="varinum" name="vari" readonly>
<br>
</form>
<hr>
ePortfolio
</body>
</html>
My javascript is as follows:
function performStatistics() {
var newarray = document.getElementById("numbers").value;
var array = newarray.split(" ");
for (var i = 0; i < array.length; i++) {
if (array[i] < 0 || array[i] > 100) {
alert("Enter positive values from 0-100")
return false;
}
}
if (array.length < 5 || array.length > 20) {
alert("Enter at least 5 values & no more than 20");
return false;
}
document.getElementById("meannum").value = calcMean(array);
document.getElementById("mednum").value = calcMedian(array);
document.getElementById("modenum").value = calcMode(array);
document.getElementById("stddev").value = calcStdDev(array);
document.getElementById("sumnum").value = calcSum(array);
document.getElementById("varinum").value = calcVariance(array);
document.getElementById("maxnum").value = findMax(array);
document.getElementById("minnum").value = findMin(array);
return false;
}
function calcMean(array) {
return calcSum(array) / array.length;
}
function calcMedian(array) {
var med = 0;
var arraylen = array.length;
arraylen.sort();
if (arraylen % 2 === 0) {
med = (array[arraylen / 2 - 1] + array[arraylen / 2]) / 2;
//takes average of an even array
} else {
med = array[(arraylen - 1) / 2];
//takes middle value of odd array
}
return med;
}
function calcMode(array) {
var mode = [];
var counter = [];
var i;
var holder;
var maxfreq = 0;
for (i = 0; i < array.length; i += 1) {
holder = array[i];
counter[array] = (counter[holder] || 0) + 1
if (counter[holder] > maxfreq) {
maxfreq = counter[holder];
}
}
for (i in counter)
if (counter.hasOwnProperty(i)) {
//returns boolean value^
if (counter[i] === maxfreq) {
mode.push(Number(i));
//pushes value into (end of) array
}
}
return mode;
}
function calcStdDev(array) {
return Math.sqrt(calcVariance(array)).toFixed(2);
}
function calcSum(array) {
var sum = 0;
for (var i = 0; i < array.length; i++) {
sum += Number(array[i]);
}
return sum.toFixed(2);
}
function calcVariance(array) {
var avg = calcMean(array);
var newarray = [];
var vari;
for (i = 0; i < array.length; i++) {
newarray[i] = (array[i] - avg) * (array[i] - avg);
}
vari = calcSum(newarray) / newarray.length;
return vari.toFixed(2);
}
function findMax(array) {
var newarray = array;
var maxnum = Math.max(newarray);
return maxnum;
}
function findMin(array) {
var newarray = array;
var minnum = Math.min(newarray)
return minnum;
}
You need to prevent the submit button from submitting the form.
window.onload=function(){
document.getElementById('subbutton').addEventListener('click', function(ev){
ev.preventDefault(); // prevent the page submit
});
}
You can remove the onclick from the HTML, and add this to your script:
// When the DOM (HTML) is ready
addEventListener('DOMContentLoaded', function() {
// When the form gets submitted (click on submit or enter key)
document.forms[0].addEventListener('submit', function (event) {
performStatistics();
// Prevent the form from refreshing the page
event.preventDefault();
});
});
Note: your script is included in the <head> of your document. Waiting for DOMContentLoaded will ensure the document is ready no matter where your script is called. But you could skip that part if you include your script at the very bottom, before the closing </body> tag.

How to accept the input from a text box and display in array format in jQuery?

I have written the code of taking input value from a text box and adding it to an array using the add button and also displaying the values of the array when the display button is clicked.
The thing is I did all this using JavaScript and now I want to do it using jQuery. I tried a code snippet from this website but it's not working. Please help.
<body>
<script src="jquery-3.3.1.js"></script>
<input type="text" id="text1"></input>
<input type="button" id="button1" value="Add" onclick="add_element_to_array();"></input>
<input type="button" id="button2" value="Display" onclick="display_array();"></input>
<div id="Result"></div>
<script>
var x = 0;
var sample = []; // <-- Define sample variable here
function add_element_to_array(){
$(document).on('click', '#btnSubmit', function () {
var test = $("input[name*='i_name']");
$(test).each(function (i, item) {
sample.push($(item).val());
});
console.log(sample.join(", "));
});
}
function display_array() {
var e = "<hr/>";
for (var y = 0; y < sample.length; y++) {
e += "Element " + y + " = " + sample[y] + "<br/>";
}
document.getElementById("Result").innerHTML = e;
}
</script>
</body>
You can use this code to get idea of how it should work. You can also check for non-empty value before pushing the value into the array as an empty value in array will not make any sense.
$(document).ready(function(){
var valueArray = [];
//add value in array
$('#button1').click(function(){
var textValue = $('#text1').val();
//push non empty value only
if(textValue.trim() !== ''){
valueArray.push(textValue);
//reset the text value
$('#text1').val('');
}
});
//display value
$('#button2').click(function(){
$('#Result').html(valueArray.toString());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text1"></input>
<input type="button" id="button1" value="Add"></input>
<input type="button" id="button2" value="Display"></input>
<div id="Result"></div>
I have added the jquery script considering the following as your suggested html.
<input type="text" id="text1"></input>
<input type="button" id="button1" value="Add"></input>
<input type="button" id="button2" value="Display"></input>
<div id="Result"></div>
The inptArr must be a global array.
<script>
var inptArr = [];
$('#button1').on('click',function(){
if($('#text1').val() != '')
inptArr.push($('#text1').val());
});
$('#button2').on('click',function(){
var string = '';
var lastIndex = parseInt(inptArr.length - 1);
for(var i = 0; i <= lastIndex ; i++)
{
if(i == lastIndex)
string += inptArr[i];
else
string += inptArr[i] + ',';
}
$('#Result').append(string);
});
</script>
This is another way to achieve what you want with minor changes.
You have only one text input element so don't need any each loop.
document.ready() is needed if you define script from starting of the code because at starting there is no defined element that have an id as btnSubmit so this block must wait to dom elements to be ready.
Also you don't need pure javascript code getElementById on display_array() function when you use jquery. You can change it as $("#Result").html(e);
var x = 0;
var array = [];
$(document).ready(function(){
$('#btnSubmit').on('click', function () {
array.push($("#text1").val());
});
});
function display_array() {
var e = "<hr/>";
for (var y = 0; y < array.length; y++) {
e += "Element " + y + " = " + array[y] + "<br/>";
}
$("#Result").html(e);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text1"/>
<input type="button" id="btnSubmit" value="Add"/>
<input type="button" id="button2" value="Display" onclick="display_array();"/>
<div id="Result"></div>
In your code functions passed to onclick attributes are binding the click event to a DOM - don't do that.
var array = Array();
var input = $("#text1");
var result = $("#result");
function add_element_to_array(){
var value = input.val();
array.push(value);
console.log("Add:", value);
// input.val(""); // bonus: clears input after adding text to an array
}
function display_array() {
result.text(array.toString());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text1">
<input type="button" id="button1" value="Add" onclick="add_element_to_array();">
<input type="button" id="button2" value="Display" onclick="display_array();">
<div id="result"></div>

Taking the sum of user inputs and storing it as a variable

What is the best way to calculate sum of user inputs from an array and then store that value as a variable?
I have a function here that creates an array from user inputs(number4[]).
var counter = 1;
var limit = 3;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Asset($) " + (counter + 1) + " <br><input type='text' name='number4[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
<div class="container7">
<div id ="dynamicInput">
Assets 1($): <INPUT type="text" name="number4[]">
</div>
Liabilities 1(%): <INPUT type="text" name="number5">
Result($): <INPUT type="text" name="total1">
<INPUT type="button" style="background-color:#FF8800; border-color:BLACK;" value="Calculate"onclick="javascript:networth()">
<INPUT type="button" style="background-color:#FF8800; border-color:BLACK;" value="Add asset fields"onclick="addInput('dynamicInput');">
</div>
</FORM>
I have no code for total1 yet. so basically i have the array i just need help identifying the sum and then assigning it as a variable.
document.getElementsByName("number4[]") will return an array of the elements you need to total up
function networth(){
var totNo = document.getElementsByName("number4[]").length;
var sum = 0;
for(var i=0; i<totNo; i++){
sum += parseInt(document.getElementsByName("number4[]")[i].value);
console.log(sum);
}
}
Add an id to your input elements and use
var val1 = document.getElementById("the id of the input you want").value
//repete for val2... with a different id and add the val variables
You need to get all the input elements you want to sum. You can use the querySelectorAll to get all the elements with a same CSS selector common in all the inputs you want to sum.
https://www.w3schools.com/jsref/met_document_queryselectorall.asp
Finally you can get the input in the same way with querySelector, as is only one there is no need to use the All variation.
https://www.w3schools.com/jsref/met_document_queryselector.asp
var counter = 1;
var limit = 3;
function networth(){
var inputs = document.querySelectorAll("form #dynamicInput input");
var networth = 0;
for (var i = 0; i < inputs.length; i++) {
networth += parseFloat(inputs[i].value);
}
document.querySelector("input[name=total1]").value=networth;
}
function addInput(divName) {
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Asset($) " + (counter + 1) +
" <br><input type='text' name='number4[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
<form>
<div class="container7">
<div id="dynamicInput">
Assets 1($):<br>
<INPUT type="text" name="number4[]">
</div>
Liabilities 1(%):
<INPUT type="text" name="number5"> Result($):
<INPUT type="text" name="total1">
<INPUT type="button" style="background-color:#FF8800; border-color:BLACK;" value="Calculate" onclick="javascript:networth()" />
<INPUT type="button" style="background-color:#FF8800; border-color:BLACK;" value="Add asset fields" onclick="addInput('dynamicInput');" />
</div>
</FORM>

GetElementById using variable is giving hard time

I am trying to use a variable to check what form ID has invoked the onClick event. I tried to go through everything on stack but I am still not sure why getElementById is returning null. Here is what my code looks like -
<form id="mul_f" name="mulf" method="post">
<select id= "mul" name="libraries">
<?php include (__DIR__ ."/include/syshost.php"); ?>
</select>
From Date:<input id="mul_fd" name="mulfd" type="date">
<button id="mulb" type="button" value="submit" onclick="display(this.form.id)"> Submit </button>
<div id="mul_chart_div"></div>
<div id="mul_table_div"></div>
</form>
my function -
function display(s) {
var x = document.getElementById(s); // returns null
var i;
for (i = 0; i < x.length; i++) { // errors out on x.length
document.write(x.elements[i].value + "<br>");
}
document.write(s.id);
document.write(x.length);
}
I tried this -
<form id="mul_f" name="mulf" method="post">
<select id= "mul" name="libraries">
<?php include (__DIR__ ."/include/syshost.php"); ?>
</select>
From Date:<input id="mul_fd" name="mulfd" type="date">
<button id="mulb" type="button" value="submit" onclick="display(this.form)">Submit</button>
<div id="mul_chart_div"></div>
<div id="mul_table_div"></div>
function -
function display(s){
document.write(s.id);
//var x = document.getElementById(s.id);
var x = s;
var i;
for (i = 0; i < x.length; i++) {
document.write(x.elements[i].value + "<br>");
}
document.write(s.id);
document.write(x.length);
}
this works now. Thanks Max, Adeneo Travis.
function onButtonClick() {
var form = getForm(this);
if (form)
alert(form.id);
}
function getForm(el) {
if (el == el.parentNode || !el.parentNode)
return null;
if (el.parentNode.tagName == "FORM")
return el.parentNode;
else
return getForm(el.parentNode);
}
window.addEventListener("load", function () {
var buttons = document.querySelectorAll("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", onButtonClick);
}
})
<form id="form1">
<button type="button">In form 'form1'</button>
</form>
<form id="form2">
<button type="button">In form 'form2'</button>
</form>
<!--Button out of from-->
<button type="button"> Out of from </button>
this refers to the button element.
onclick="display(document.forms[0].id)">

Why is my JavaScript function not returning the checked array value?

In the following code, my alert() is returning 0 when it should be returning the checked box value. I need it to return the value in the designated array associated with the checkbox.
<!DOCTYPE html>
<html>
<head> <title> Program 4 Parallel Arrays </title>
<style type="text/css"></style>
<script type="text/javascript">
var priceArray = [45.25, 24.88, 32.35, 27.33,
34.85, 36.24, 85.33, 45.32];
var pageArray = [1098, 536, 500, 792, 912, 1224, 899, 504];
function funRun () {
var totalPages = 0;
for(i=0; i<document.bookForm.books[i].length; i++) {
if(document.bookForm.books[i].checked == true) {
totalPages = totalPages + pageArray[i];
}
}
alert("totalPages : " + totalPages);
}
function funRun1 () {
var subTotal = 0;
for(i=0; i<document.bookForm.books[i].length; i++) {
if(document.bookForm.books[i].checked == true) {
subTotal = subTotal + priceArray[i];
}
}
alert("subTotal : " + subTotal);
}
tax = (.06 * subTotal)
total= (subTotal + tax)
</script>
</head>
<body>
<form name="bookForm">
<input type="checkbox" name="books" value="Flanagan" />
JavaScript, the Definitive Guide: $45.25 <br>
<input type="checkbox" name="books" value="McFarland" />
JavaScript & JQuery: The Missing Manual: $24.88 <br>
<input type="checkbox" name="books" value="Morrison" />
Head First JavaScript: $32.35 <br>
<input type="checkbox" name="books" value="Wilton&McPeak" />
Beginning JavaScript: $27.33 <br>
<input type="checkbox" name="books" value="Quigley" />
JavaScript by Example: $34.85 <br>
<input type="checkbox" name="books" value="Goodman" />
JavaScript Bible: $36.24 <br>
<input type="checkbox" name="books" value="Gosselin" />
JavaScript: The Web Technologies Series: $85.33 <br>
<input type="checkbox" name="books" value="Suehring" />
JavaScript Step by Step: $45.32 <br>
<br>
<input type="button"
value="Calculate Total"
onclick="funRun();funRun1()"/>
<input type="reset"/>
<br>
<br>
<input type="text" name="totalPages"/>Total Pages<br>
<input type="text" name="subTotal"/>Subtotal<br>
<input type="text" name="tax"/>Tax<br>
<input type="text" name="total"/>Total</p>
</body>
</html>
The issue is at your for loop.
Use:
for(i=0; i<document.bookForm.books.length; i++) {
Instead of:
for(i=0; i<document.bookForm.books[i].length; i++) {
The reason is that you should not access the array element at the size definition.
Also, the following block is returning a ReferenceError since the subTotal variable was not defined out of the funRun1() function:
tax = (.06 * subTotal)
total= (subTotal + tax)
I would change your funRun() to this
function funRun () {
var inputs = document.forms[0].querySelectorAll('[name=books]');
var totalPages = 0;
for(i=0; i<inputs.length; i++) {
if(inputs[i].checked) {
totalPages = totalPages + pageArray[i];
}
}
alert("totalPages : " + totalPages);
}
Apply the same to funRun1() and you'll be fine.
Also, an error is raised in the console because of this
tax = (.06 * subTotal)
total= (subTotal + tax)
The reason is that your subTotal scope is only in funRun1()
I would even suggest putting your script just before the </body>
apart from the changes suggested by Zanon, take these two lines inside the function funrun1() -
tax = (.06 * subTotal)
total= (subTotal + tax)
Also, I would suggest you to call funrun1() from inside funrun() onclick event of the button.
The issue is that when you are indexing with i inside your for loop it is 0 at that time which means that your loop won't iterate at all. Therefore,
Change:
for(i=0; i<document.bookForm.books[i].length; i++) {
if(document.bookForm.books[i].checked == true) {
totalPages = totalPages + pageArray[i];
}
}
To:
for(i=0; i<document.bookForm.books.length; i++) {
if(document.bookForm.books[i].checked == true) {
totalPages = totalPages + pageArray[i];
}
}
and Change
for(i=0; i<document.bookForm.books[i].length; i++) {
if(document.bookForm.books[i].checked == true) {
subTotal = subTotal + priceArray[i];
}
}
To:
for(i=0; i<document.bookForm.books.length; i++) {
if(document.bookForm.books[i].checked == true) {
subTotal = subTotal + priceArray[i];
}
}
In addition, here is a working JS Fiddle for you.
https://jsfiddle.net/Kitchenfinks/5ovkdh2c/
Happy Coding!

Categories

Resources