Assistance with using loops - javascript

Basically I'm trying to create a function in which it takes parameters, the times table required, and the values at which it should start and end. The function is to return a formatted string that can be displayed in the output area.
The rest of the code will get the three values from the textboxes and call the multiplication table function.
The return value will be displayed in a text area.
An example of what it should look like:
My JS currently looks like this:
function btnDisplay_onclick()
{
// get textboxes and assign to variables
var tableTextbox = document.getElementById("txtTable");
var startTextbox = document.getElementById("txtStart");
var finishTextbox = document.getElementById("txtFinish");
var outputTextbox = document.getElementById("txtOutput");
var table = tableTextbox.value;
var start = startTextbox.value;
var finish = finishTextbox.value;
var output = multiply(table, start, finish);
outputTextbox.value = output;
}
function multiply(table, start, finish)
{
for
}
the HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<!-- saved from url=(0014)about:internet -->
<title>Multiplication Table</title>
<script src="Lab6-MultTable.js"></script>
</head>
<body>
<form action=#>
<p><h1>Multiplication Table</h1></p>
<p>
Table Number:<input type="text" id="txtTable"><br>
Start Number:<input type="text" id="txtStart"><br>
Finish Number:<input type="text" id="txtFinish"><br>
</p>
<p>
<textarea id="txtOutput" rows="8" cols="20" readonly="readonly"></textarea>
</p>
<p>
<input type="button" value="Display Numbers" id="btnDisplay" onclick="btnDisplay_onclick()">
<input type="reset">
</p>
</form>
<noscript>This website requires JavaScript to be enabled.</noscript>
</body>
</html>
So basically I'm having trouble learning how to use Loops properly if someone would be willing to explain it to me as reading up on it I'm not able to fully understand it for whatever reason.

You could change the processing of the value a bit, like
var table = +tableTextbox.value || 0;
That converts the value to number and checks for a truthy value. If falsy, take zero as value.
For multiplication take the start and end value for the for loop and a variable for the result.
Calculate the value and add the line to the result, return the result.
function multiply(table, start, finish) {
var i, result = '';
for (i = start; i <= finish; i++) {
result += table + ' * ' + i + ' = ' + table * i + '\n';
}
return result;
}
function btnDisplay_onclick() {
// get textboxes and assign to variables
var tableTextbox = document.getElementById("txtTable");
var startTextbox = document.getElementById("txtStart");
var finishTextbox = document.getElementById("txtFinish");
var outputTextbox = document.getElementById("txtOutput");
var table = +tableTextbox.value || 0; // convert to number and
var start = +startTextbox.value || 0; // testfor truthynes or take
var finish = +finishTextbox.value || 0; // the default value of 0
var output = multiply(table, start, finish);
outputTextbox.value = output;
}
function multiply(table, start, finish) {
var i, result = '';
for (i = start; i <= finish; i++) {
result += table + ' * ' + i + ' = ' + table * i + '\n';
}
return result;
}
<form action="">
<p><h1>Multiplication Table</h1></p>
<p>
Table Number:<input type="text" id="txtTable"><br>
Start Number:<input type="text" id="txtStart"><br>
Finish Number:<input type="text" id="txtFinish"><br>
</p>
<p>
<textarea id="txtOutput" rows="8" cols="20" readonly="readonly"></textarea>
</p>
<p>
<input type="button" value="Display Numbers" id="btnDisplay" onclick="btnDisplay_onclick()">
<input type="reset">
</p>
</form>

Another way is write the result inside the loop at textarea.
$("#display").on("click", function(){
multiply();
});
function multiply(){
var table = document.getElementById("table").value
, start = document.getElementById("start").value
, finish = document.getElementById("finish").value
, text = document.getElementById("result");
text.value = '';
for ( var i = start ; i <= finish ; i++ ){
text.value += table + " * " + i + " = " + (table * i) + "\n";
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<div id="parameters">
Table number: <input id="table" type="number" />
<br/>
Start number: <input id="start" type"number" />
<br/>
Finish number: <input id="finish" type"number" />
<div>
<textarea id="result" rows="8" cols="20" readonly="readonly"></textarea>
</text>
<br/><br/>
<button id="display" /> Display numbers
<button type="reset" /> Reset
</form>

Related

Generate user id using javascript and display it in textbox

So i need to display the user id that has been generated in javascript but i have problem to display it on textbox.
here's the javascript coding:
function AddDetails(){
var button = document.getElementById('button');
button.addEventListener('click', SaveDetails, false);
}
function SaveDetails(){
var CreateuserID = generateuserID();
document.getElementById('userID').value = CreateuserID;
var name = document.getElementById('userName').value;
var occupation = document.getElementById('userOccupation').value;
sessionStorage.setItem(name, occupation);
display();
var name = document.getElementById('userName').value = "";
var occupation = document.getElementById('userOccupation').value = "";
}
function display(){
var output = document.getElementById('output');
output.innerHTML = "";
for(var i=0;i<sessionStorage.length;i++)
{
var name = sessionStorage.key(i);
var occupation = sessionStorage.getItem(name);
output.innerHTML += name+"|"+occupation+"<br>";
}
}
function generateuserID()
{
var userIDnum = 1;
userIDnum++;
}
window.addEventListener('load', AddDetails, false);
This is the HTML code:
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="Style.css">
<script src="script.js"></script>
</head>
<br>
<body>
<section id="input">
<form>
ID : <input type="number" readonly id="userID" value="">
Name : <input type="text" id="userName" >
Occupation : <input type="text" id="userOccupation">
<input type="button" id="button" value="Add">
</form>
</section>
<br>
<br>
Sort by: <select name="sort">
<option value ="userID">userID</option>
<option value ="userID">userName</option>
<option value ="userID">userOccupation</option>
</select>
<br>
<section id="output">
</section
</body>
</html>
Please help me i have been doing this for days and cant think of solution. I tried using ECMAScript and it wont work either. I'm still new and lack of knowledge.
Your generateuserID() method doesn't return anything. Even if your returned userIDnum everyone's user id will be 2. Do you realize that JavaScript just runs in the browser? None of the variables will exist between different users.
There are many mistakes in your sample. You don't need sessionStorage just for static content. Here is the working codepen [ https://codepen.io/vivekamin/pen/gQMRPx ] .I have created for you from your code. Please check it out. Here is the code. I have used createElement just for sake of working example. However, if you have many elements to append you can use createDocumentFragment which is more efficient. I am just adding the last data to HTML, output element in form of paragraph text
HTML:
<body>
<section id="input">
<form>
ID : <input type="number" readonly id="userID" value="">
Name : <input type="text" id="userName" >
Occupation : <input type="text" id="userOccupation">
<input type="button" id="button" value="Add">
</form>
</section>
<br>
<br>
Sort by: <select name="sort" id ="sortBy">
<option value ="userID">userID</option>
<option value ="name">userName</option>
<option value ="occupation">userOccupation</option>
</select>
<br>
<section id="output">
</section
</body>
JS Code:
let counter = 1;
let data = [];
function AddDetails(){
var button = document.getElementById('button');
button.addEventListener('click', SaveDetails, false);
let sortBy = document.getElementById('sortBy');
sortBy.addEventListener('change', SortAndDisplay, false);
document.getElementById('userID').value = counter;
}
function SortAndDisplay(){
console.log("Sorting", document.getElementById('sortBy').value);
let sortBy = document.getElementById('sortBy').value;
if(sortBy === "userID"){
data.sort(function (a, b) {
return a.id - b.id;
});
}
else{
sortByNameOrOccupation(sortBy);
}
console.log(data);
displayAfterSort();
}
function SaveDetails(){
let name = document.getElementById('userName');
let occupation = document.getElementById('userOccupation');
data.push({id: counter, name: name.value, occupation: occupation.value });
console.log(data);
counter++;
document.getElementById('userID').value = counter;
name.value='';
occupation.value ='';
let outputSection = document.getElementById('output');
let outputData = data[data.length - 1];
let newP = document.createElement('p');
newP.textContent = outputData['id'] + " " + outputData['name'] + " "+outputData['occupation'];
outputSection.appendChild(newP);
}
function sortByNameOrOccupation(attribute){
data.sort(function(a, b) {
var nameA = a[attribute].toUpperCase(); // ignore upper and lowercase
var nameB = b[attribute].toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
});
}
function displayAfterSort(){
let outputSection = document.getElementById('output');
outputSection.innerHTML = '';
let fragment = document.createDocumentFragment();
data.forEach(function(d) {
let p = document.createElement('p');
p.textContent = d['id'] + " " + d['name'] + " "+d['occupation'];
fragment.appendChild(p);
});
outputSection.appendChild(fragment);
}
window.addEventListener('load', AddDetails, false);
To set the value of the textbox. Do:
$('#//ID of the textbox').val(CreateuserID)
This is assuming that 'CreateuserID' is a string or int
EDIT: Your CreateuserID function will need to return a value.

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>

How to store inputs from a textbox in array in Javascript

<!DOCTYPE html>
<html>
<head>
<form id="form1">
Beets:<input id="number1" type="integer" size = "5">
Artichokes: <input id="number2" type="integer" size = "5">
Carrots: <input id="number3" type="integer" size = "5">
</form>
<button id = "submitButton" onclick="RunApp()" > Submit</button>
<button id = "displayButton" onclick="getAllValues()" > Display</button>
<script>
var str = "";
function getAllValues() {
var input1, inputs;
input1 = document.getElementById("form1");
inputs = input1.elements["number1"].value;
for (i = 0; i < inputs.length; i++) {
str += inputs[i].value + " ";
}
alert(str);
}
function RunApp()
{
var beets, artichokes, carrots, input1, input2, input3;
// getting inputs into variables
input1 = document.getElementById("form1");
beets = input1.elements["number1"].value;
input2 = document.getElementById("form1");
artichokes = input1.elements["number2"].value;
input3 = document.getElementById("form1");
carrots = input1.elements["number3"].value;
if (beets == "" || carrots == "" || artichokes == "" || isNaN(beets) || isNaN(carrots) || isNaN(artichokes))
{
document.getElementById("demo").innerHTML+= "not valid" + "<br>";
document.getElementById("demo").innerHTML+= "--------------------------" + "<br>";
}
else
{
document.getElementById("demo").innerHTML+= "Beets = " + beets + "<br>"; document.getElementById("demo").innerHTML+= "Artichokes = " + artichokes + "<br>";
document.getElementById("demo").innerHTML+= "Carrots = " + carrots + "<br>";
}
}
</script>
<p id="demo"></p>
</head>
<body>
</body>
</html>
First, this is my first time learning JS.
So, I have a text-box, a submit button, and a display button. When I enter a number in the text-box, and click submit, it shows the number. I enter my second number and clicking the submit button shows me the second number. Then I click on the display button, it will shows the number 1 and number 2 in order. If I have more inputs in the text-box, the display button will show the entire list of all the inputs from the array.
Thank you!
Well, since it's your first time and you're learning I won't just give you the answer, but I'll point you in the right direction.
You want to attach a click event on the submit button to add the value to an array, and then print the array on click of the display button.
i think first you must google for this. I write something and you can improve this. I only want to give an example.
HTML:
<input type="text" id="inputbox">
<br/>
<button type="button" id="submit">Submit</button>
<button type="button" id="display">Display</button>
<br/>
<div id="screen"></div>
JS:
var inputArray = [];
var input = document.getElementById('inputbox');
var screen = document.getElementById('screen');
document.getElementById('submit').onclick = function () {
inputArray.push(input.value);
screen.innerHTML = input.value;
};
document.getElementById('display').onclick = function () {
screen.innerHTML = inputArray
};
http://jsfiddle.net/y9wL27y0/

Dynamically array input with Javascript

I want to input the amount of array and the output will follow as it's amount.
Ex: If I put "7" in the input text. the result will show as much as 7.
Here's my code:
<html>
<head>
<title>JavaScript - Input Text Field</title>
</head>
<body>
<form name="test">
<H2>Enter something into the field and press the button. <br></H2>
<P>Amount of Tables: <input type="TEXT" name="amount"><BR><BR>
<input type="Button" Value="Show and Clear Input" onClick="myFunction()"></P>
</form>
<p id="demo"></p>
<script>
function myFunction() {
var text = "";
var i;
var j = document.getElementsByName("amount");
for (i = 0; i < j.length; i++) {
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
You have something wrong on your JavaScript
See code:
function myFunction() {
var text = "";
var i;
var j = document.getElementsByName("amount")[0];
for (i = 0; i < j.value; i++) {
text += "The number is " + j.value + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
.getElementsByName returns an array of elements, so you need to specify the index of your element so that you can access its properties.
Fiddle here

Can't update array correctly in javascript... logic error?

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>MultipleOf</title>
<script>
var sales = new Array(9); //array for keeping sales numbers
var pay = ["200-299","300-399","400-499","500-599","600-699","700-799","800-899","900-999","1000 and over"];
var tally = new Array(9); //array for keeping statistics
result=""; //for table creation
temp="";
for(i=0; i<9; i++){ //initialize empty arrays of numbers
tally[i] =0;
sales[i] =0;
}
function start(){ //button to launch everything
var button = document.getElementById("clickButton");
button.addEventListener("click", giveResult, false);
}
function giveResult(){ //is supposed to calculate sales and add one to the tally the position which the sale belongs.
for(var i=0; i<9; i++){
temp="e"+i;
sales[i]= parseInt(document.getElementById(temp)); //Grab info from form (currently from first field)
sales[i]=paid(sales[i]); //calculate pay for sales made and overwrite sales amount
var placement = decide(sales[i]); //decide which statistic to increment according to amount paid
tally[placement]= tally[placement]+1; //increment statistic
}
var result = document.getElementById("result");
temp = display(result);
result.innerHTML = temp;
}
function paid(salesAmount){
return 200+(salesAmount*0.09);
}
function decide(amountPaid){
if(amountPaid>1000)
return 8;
else if(amountPaid>900)
return 7;
else if(amountPaid>800)
return 6;
else if(amountPaid>700)
return 5;
else if(amountPaid>600)
return 4;
else if(amountPaid>500)
return 3;
else if(amountPaid>400)
return 2;
else if(amountPaid>300)
return 1;
if(amountPaid>=200)
return 0;
else
return -1;
}
function display(value){
value = "<table>"
for(var i=0;i<pay.length; i++){
value = value + "<tr><td>" + pay[i] + "</td>" + "<td>" + tally[i] + "</td>" ;
}
value = value + "</table>";
return value;
}
window.addEventListener("load",start,false);
</script>
</head>
<body>
<form action="#">
<p><label>Enter Employee Sales for the week:</label></p>
<p>Employee 1:<input id="e1" type="number" value="0"></p>
<p>Employee 2:<input id="e2" type="number" value="0"></p>
<p>Employee 3:<input id="e3" type="number" value="0"></p>
<p>Employee 4:<input id="e4" type="number" value="0"></p>
<p>Employee 5:<input id="e5" type="number" value="0"></p>
<p>Employee 6:<input id="e6" type="number" value="0"></p>
<p>Employee 7:<input id="e7" type="number" value="0"></p>
<p>Employee 8:<input id="e8" type="number" value="0"></p>
<p>Employee 9:<input id="e9" type="number" value="0"></p>
<p><input id = "clickButton" type="button" value = "Calculate"></p>
</form>
<p id = "result"></p>
<footer>
<p>
</p>
</footer>
</body>
I am hoping to input sales numbers into a form, then calculate the earnings for each employee using the function paid(), and then to take those earnings and sort them into a table with ranges such as defined by the pay array.
The problem is I am not sure what I am doing wrong, is it my paid() function that is messing up the counters?
The tally array is not being updated correctly and I am not sure why.
sales[i]= parseInt(document.getElementById(temp)); //Grab info from
form (currently from first field)
Try parseInt(document.getElementById(temp).value, 10) instead.
The line that has sales[i]= parseInt(document.getElementById(temp)); is using parseInt against an element, try using this instead to get the value of the input field:
sales[i]= parseInt(document.getElementById(temp).value);

Categories

Resources