JS:
function myarray (){
}
var starting=document.getElementById("starting");
var ending=document.getElementById("ending");
var step=document.getElementById("step");
var results=document.getElementById("myarray")
if (i>=0){
var result=starting
}
for (var starting>=0; myarray<=ending; i+=step)
document.writeln(myarray[i+=step]){
}
HTML:
<div id="results">Here are the even numbers between "startingnumber" and "endingnumber" by "step"&nnsp's
<!DOCTYPE html>
<html>
<head>
<title>A Web Page</title>
</head>
<script src="Guild_Practice.js"></script>
<style media="screen">
table {
width:40%;
}
.titles {
text-align: right;
color: green;
font-family: arial;
font-weight: bold;
padding-bottom: 10px;
}
caption {
font-size: 32px;
font-weight: bold;
font-family: cursive;
color: red;
}
.displayevens {
text-align: center;
padding-top: 10px;
}
}
</style>
<body>
<table>
<caption>Sample</caption>
<form>
<tr>
<!--Starting Number Line with Form -->
<td class="titles">Starting Number</td>
<td class="align-left"><input type="text" id="starting"></td>
</tr>
<tr>
<!-- Ending Number Line with Form -->
<td class="titles">Ending Number</td>
<td class="align-left"><input type="text" id="ending"></td>
</tr>
<tr>
<!-- Step Line with Form -->
<td class="titles">Step</td>
<td class="align-left"><input type="text" id="step"></td>
</tr>
<tr>
<!-- Button covered in both columns -->
<td class="displayevens" colspan="2"><button type="button">Display Evens</button></td>
</tr>
</form>
</table>
</body>
</html>
I have to allow a user to enter a starting number an ending number and a step value into three textboxes on a page (which I have created). A button will be present that when clicked should output all the even numbers between the start and end value.
My questions are:
How does my js code look so far?
How do I make a phrase such as: "Here are the even numbers between 4 and 20 by 3's" and then list out the numbers. It will appear once I click the button.
You could take the values and cast it to number with an unary plus and iterate from starting to ending with the given step. With each loop check if the actual counter is even and add it to the result set.
Later display the result in results.
function myarray() {
var starting = +document.getElementById("starting").value,
ending = +document.getElementById("ending").value,
step = +document.getElementById("step").value,
results = document.getElementById("results"),
i,
array = [];
for (i = starting; i <= ending; i += step) {
i % 2 || array.push(i);
}
results.innerHTML = array.join(', ');
}
<pre><form>Starting Number: <input type="text" id="starting"><br>Ending Number: <input type="text" id="ending"><br>Step: <input type="text" id="step"><br><button type="button" onclick="myarray()">Display Evens</button></form><div id="results"></div></pre>
So it isn't so much that you want the even numbers, you simply want the incremental steps between your starting and ending point. Is that correct? And I assume this is a school assignment? Try something like this to kick you off. I've created the HTML elements, and I've retrieved the values of the inputs. Now you get to create the logic for the increment (try a FOR loop) and insert the results into the progression-pane.
/*****
* When the "show me!" button gets clicked,
* there's a few things we do: get the values of
* the inputs, loop from the starting value to
* the ending value by a given increment (default
* increment of two), and output the result to a div.
*****/
runCounter = function() {
// This is the location we'll put the result
var contentPane = document.getElementById("progression-pane");
// This will be the output string
var contentString = "";
// retrieve the values given AND MAKE THEM
// INTEGERS! We could do floats, but it's
// darn important to make them numbers.
var startingValue = parseInt(document.getElementById("startingValue").value);
var endingValue = parseInt(document.getElementById("endingValue").value);
var increment = parseInt(document.getElementById("incrValue").value);
if (startingValue && endingValue) {
// So long as we actually HAVE a staring and ending value...
if (!increment) increment = 2;
// If we don't have an increment given, let's count by twos!
contentString += "<p>The values between " + startingValue + " and " + endingValue + " in increments of " + increment + ":</p><ul>";
for (i = startingValue; i <= endingValue; i += increment) {
// If we are here, we have all three: start, end and increment
contentString += "<li>" + i + "</li>";
}
contentString += "</ul>";
// We've finished formatting the string,
// let's output it to the proper div.
// Note that I'm using innerHTML,
// document.writeln is considered bad.
contentPane.innerHTML = contentString;
}
}
label {
display: block;
font-weight: bold;
}
<label for="startingValue">Start:</label>
<input type="text" id="startingValue" />
<label for="endingValue">End:</label>
<input type="text" id="endingValue" />
<label for="startingValue">Increment:</label>
<input type="text" id="incrValue" />
<button onclick="runCounter()">Show me!</button>
<div class="content-pane">
<h2>Your progression:</h2>
<div id="progression-pane">
</div>
</div>
The bulk of the above javascript is actually comments discussing what I'm doing. Get in that habit, so you don't lose track of variables! And yours works fine, but innerHTML is considered better form than document.writeln
Ok, so if in fact you want the EVEN numbers at the given step intervals, change the line that actually appends the line items like this:
// Now, we want to see if this is an even number
if(i%2 == 0)
contentString += "<li>" + i + "</li>";
See this version running as a fiddle here
Related
I am trying to create a loop. so far I can get it to say Hello Tom and just the number. I want to add on a function named addOrderListItems that receives the name and numOfTimes as parameters. Then call the addOrderListItems function from the displayHello function and if the number is even add an !
so if I type name Braden and numOfTimes 8
the output will display a list
1.Hello Braden
2.Hello Braden!
3.Hello Braden
4.Hello Braden!
5.Hello Braden
6.Hello Braden!
7.Hello Braden
8.Hello Braden!
9.Hello Braden
function displayHello() {
let name = document.getElementById("helloNameInput").value,
numOfTimes = document.getElementById("numOfTimesInput").value;
}
function addOrderListItems() {
let numOfTimes = 0;
while (numOfTimes > 0 ) {
document.getElementById("helloNameOutput").innerHTML = "Hello " + name + numOfTimes;
numOfTimes++;
}
}
function clearName() {
document.getElementById("helloNameInput").value = "";
document.getElementById("numOfTimesInput").value = "";
document.getElementById("helloNameOutput").innerText = "";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>JavaScript: Looping Structures Assignment</title>
<link href="/bootstrap.min.css" rel="stylesheet" />
</head>
<body class="p-3">
<h1>JavaScript: Looping Structures Assignment</h1>
<!--Name input-->
<div class="mb-3">
<label for="helloNameInput" class="form-label">Name:</label>
<input
type="text"
class="form-control"
name="helloNameInput"
id="helloNameInput"
placeholder="Enter a name"
/>
</div>
<!--Number of Times input-->
<div class="mb-3">
<label for="numOfTimesInput" class="form-label">Number of Times:</label>
<input
type="text"
class="form-control"
name="numOfTimesInput"
id="numOfTimesInput"
placeholder="Enter number"
/>
</div>
<!--Name output-->
<ol id="helloNameOutput"></ol>
<!--Display Hello! & Reset buttons-->
<div>
<button class="btn btn-primary" id="displayHelloButton" onclick="displayHello();" >
Display Hello!
</button>
<button class="btn btn-danger" id="clearButton" onclick=" clearName();">Clear</button>
</div>
<script src="/script.js"></script>
</body>
</html>
```
You'll probably need a few functions to help you accomplish your goal and keep your code organized. Below I've created an example in a code snippet to demonstrate how the functionality you described can be implemented. I've included lots of comments to explain and help you understand the steps involved.
You can search on MDN and read the JavaScript documentation if there are parts you've never seen or don't yet understand — for example, here are a few links to some of the DOM APIs used:
Document.createElement()
Element.remove()
Node.firstChild
Node.appendChild()
Keep learning, and good luck in your programming!
const nameInput = document.getElementById('helloNameInput');
const qtyInput = document.getElementById('numOfTimesInput');
const btn = document.getElementById('writeGreeting');
const output = document.getElementById('helloNameOutput');
function createGreetingText (name, withExclamationPoint) {
return `Hello ${name}${withExclamationPoint ? '!' : ''}`;
}
function createGreetingListItem (name, withExclamationPoint) {
const listItem = document.createElement('li');
listItem.textContent = createGreetingText(name, withExclamationPoint);
return listItem;
}
function clearOutput () {
// Delete every child element from the output element:
while (output.firstChild) {
output.firstChild.remove();
}
}
function writeGreeting () {
// Get the trimmed input value (or use "world" if it's empty):
const name = nameInput.value.trim() || 'world';
// Get the number of times (quantity) from the other input:
let qty = parseInt(qtyInput.value);
// If the number input value couldn't be parsed as a valid integer,
// use 1 as the default valid value and update the input:
if (!Number.isInteger(qty)) {
qty = 1;
qtyInput.value = 1;
}
clearOutput();
// Loop the number of times:
for (let i = 1; i <= qty; i += 1) {
// Create and append a list item element each time:
const isEven = i % 2 === 0;
const listItem = createGreetingListItem(name, isEven);
output.appendChild(listItem);
}
}
// Bind the "writeGreeting" function to the button's "click" event,
// so that it runs each time the button is clicked:
btn.addEventListener('click', writeGreeting);
#container {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 1rem;
font-family: sans-serif;
}
button, input {
font-size: 1rem;
padding: 0.5rem;
}
<div id="container">
<input
type="text"
id="helloNameInput"
placeholder="name"
value="Braden"
/>
<input
type="number"
step="1"
min="1"
id="numOfTimesInput"
placeholder="# of times"
value="8"
/>
<button id="writeGreeting">Write greeting</button>
<ol id="helloNameOutput"></ol>
</div>
I'm practicing JavaScript with the jQuery library.
What I want is to create something like a POS Application, but there are things I just can't figure out.
I'd like to, if you enter lays, and then you enter lays again, the output should change to the already appended output to lays * 2.
I'm kind of lost on how to achieve the desired.
What I have so far:
var billoutput = document.getElementById('inputterminal');
var counter = 1;
$('#bill').click(function() {
$("#holder").append(" <span style='padding:10px; margin:5px; color:white; background-color:black; border-radius: 10px;'> " + billoutput.value + " </span> ");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>POS Terminal</h1>
<input id="inputterminal" value="" name="" type="text">
<button id="bill">bill</button> <br>
<div style="margin-top: 20px;" id="holder"></div>
You can store the inputs in an array and check whether the array includes the value of the input every time the user clicks the button. If it does not, append the element and push the input's value to the array.
var billoutput = document.getElementById('inputterminal');
var counter = 1;
var words = []
$('#bill').click(function() {
if (!words.includes(billoutput.value)) {
words.push(billoutput.value)
$("#holder").append(" <span style='padding:10px; margin:5px; color:white; background-color:black; border-radius: 10px;'> " + billoutput.value + " </span> ");
}else{
alert("you already entered that!")
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>POS Terminal</h1>
<input id="inputterminal" value="" name="" type="text">
<button id="bill">bill</button> <br>
<div style="margin-top: 20px;" id="holder"></div>
I am having trouble trying to convert this into an array. I don't fully understand how to take input from a form and save it in an array.
My project states: Do NOT save the input in a set of variables and then put those in an array.
Use the array as your collection of data saving variables. (That is what a data
structure is for.)
I have looked for the last 2 hours trying to find something to help me. I have to do this project in JavaScript, but keep finding jquery and I'm not quite sure on how to convert it to Javascript
Any suggestions on how I can take the form input and save it in an array?
This is only a little bit of my project. I just took the first function and the HTML that is attached to the function.
Code in the snippet.
function getID() {
var studentID = new Array();
studentID = document.forms["getFormInfo"]["txtStudentID"].value;
var numberOnly = /^[0-9]+$/;
//Checks for a null/blank within Student ID: field.
if (studentID.length == 0) {
document.getElementById('divAllField').style.display = '';
document.forms["getFormInfo"]["txtStudentID"].focus();
return false;
} //End of if statement
else {
if (studentID.length == 8 && studentID.match(numberOnly)) {
//Run the next function
getFirstName();
} //End of else/if statement
else {
//Show Error Message
document.getElementById('divStudentID').style.display = "";
//Focus on input field with the error.
document.forms["getFormInfo"]["txtStudentID"].focus();
} //end of else/if/else statement
} //End of else statement
} //End of function getID()
h1 {
text-align: center;
color: teal;
}
table {
border-spacing: 8px;
border: 2px solid black;
text-align: justify;
}
th {
text-align: center;
padding: 8px;
color: blue;
font-size: 125%;
}
td {
padding: 5px;
}
input,
select {
width: 200px;
border: 1px solid #000;
padding: 0;
margin: 0;
height: 22px;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
input {
text-indent: 2px;
}
label {
float: left;
min-width: 115px;
}
div {
padding: 3px;
color: red;
font-size: 80%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Begining of the header -->
</head>
<!-- End of the header -->
<body>
<!-- Everything in the <body> </body> displays on the webpage -->
<form id="getFormInfo">
<!-- Creates a form with an ID -->
<table id="tableInfo">
<!-- Creates a table within the form -->
<!-- Creates a table header within the form and table -->
<th>User Information</th>
<!-- Error Message for all fields if they are null/blank -->
<tr>
<td><strong><div id="divAllField" style="display: none;">
Please make sure all input boxes are filled out.
</div></strong>
</td>
</tr>
<!-- Student ID Input -->
<tr>
<td><strong><label>Student ID:</label></strong>
<input type="text" name="txtStudentID" maxlength="8" placeholder="8 Digit ID" value="00149371" required>
<!-- Error Message for Student ID -->
<strong><div id="divStudentID" style="display: none;">
Please enter your 8 Digit Student ID. (Whole Numbers Only)</br>
Example: 00123456
</div></strong>
</td>
</tr>
<tfoot>
<td>
<input type="button" onclick="getID();" value="Submit">
</tfoot>
</td>
</table>
<!-- End of tableInfo -->
</form>
<!-- End of getInfo -->
</body>
</html>
Anyone know how I can save the input from the form and save it into an array?
Please help, I've been working on this project for over 10 hours.
Use the push function to add items to the array.
function getID() {
var studentID = [];
var tstStudentIdVal = document.forms["getFormInfo"]["txtStudentID"].value
studentID.push(tstStudentIdVal);
var numberOnly = /^[0-9]+$/;
//Checks for a null/blank within Student ID: field.
if (tstStudentIdVal.length == 0) {
document.getElementById('divAllField').style.display = '';
document.forms["getFormInfo"]["txtStudentID"].focus();
return false;
} //End of if statement
else {
if (tstStudentIdVal.length == 8 && tstStudentIdVal.match(numberOnly)) {
//Run the next function
getFirstName();
} //End of else/if statement
else {
//Show Error Message
document.getElementById('divStudentID').style.display = "";
//Focus on input field with the error.
document.forms["getFormInfo"]["txtStudentID"].focus();
} //end of else/if/else statement
} //End of else statement
} //End of function getID()
If you can't use jQuery, I think the most elegant solution is to use querySelectorAll() to get a nodeList of all your inputs, then use a combination of Function.prototype.call() and Array.prototype.map() to translate the array of inputs into an array of your own design.
In the snippet below, the resulting array has objects each which have a name and value, which come directly from the text inputs in your form (your question isn't quite clear on how the resulting array should look).
function getID() {
var nodes = document.forms["getFormInfo"].querySelectorAll("input[type='text']");
var array = [].map.call(nodes, function(item) {
return {name : item.name, value : item.value};
});
console.log(array);
}
<form id="getFormInfo">
<input type="text" name="txtStudentID"/>
<input type="text" name="firstName"/>
<input type="text" name="lastName"/>
<input type="button" onclick="getID();" value="Submit"/>
</form>
I am trying to make a application with JavaScript.
The app should have a plus, a minus button, and a clear button. In the middle there should be an input where a number will appear.
The app will start off with 1000 and plus will increase by 1000, the minus button will decrease it by 1000, and the clear button will reset the application. The minimum number in the app should be 1000.
I have figured out most but the plus button is not working as it should and I cannot get the app to have 1000 as minimum, it just continues into minus.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Application</title>
</head>
<style>
#application{
margin-top: 300px;
margin-left: 300px;
}
input[type=button]{
cursor: pointer;
padding: 10px 30px;
border-radius: 1px;
font-size: 2.5em;
}
input[type=text]{
padding: 10px 30px;
border-radius: 1px;
text-align: center;
font-size: 2.5em;
}
</style>
<body>
<section id="application">
<input id="substraction" type="button" value="-" onclick='substraction();'/>
<input id="number" value="1000" type="text">
<input id="addition" type="button" value="+" onclick='addition();'/>
<input type="button" value="Clear" onclick='clearText();'/>
</section>
<script>
function substraction(){
document.getElementById("tall").value -= 1000;
}
function addition(){
var numb = document.getElementById("number").value;
var add = 1000;
var total = number + add;
document.getElementById("tall").value = total;
}
function clearText(){
document.getElementById("number").value = "1000";
}
</script>
</body>
Just use a number <input> instead:
function clearText(){
document.getElementById("myNumber").value = 1000;
}
<input id="myNumber" type="number" step="1000" min="1000" max="1000000" value="1000">
<input type="button" value="Clear" onclick='clearText();'/>
This way, you can just use the step, min, and max attributes to specify the behavior of the input.
In Javascript + is also a string concatenation operator. If at least one of the operands is a String then the result is going to be a String also. You need to cast to Number type explicitly, because input value is always of a String type, even if it looks like a number "1000":
function addition() {
var number = Number(document.getElementById("number").value);
var add = 1000;
var total = number + add;
document.getElementById("tall").value = total;
}
Also instead of var numb you probably want var number.
In addition to the other answer, you're doing document.getElementById("tall").value = total; but no element with id "tall" exists. Perhaps it should be "number"?
In order to implement the minimum use the following code in subtract:
var number = Number(document.getElementById("number").value);
if(number - 1000 >= 1000)
document.getElementById("tall").value -= 1000;
I am trying to create a loan calculator that uses commas to separate every third number. For example, $1,000,000.75.
Is there a way to display all of the input values like this, without compromising the actual calculation of numbers?
Right now, if a comma is entered in any of the inputs, than the calculated input (input that displays the calculation), throws an error (NaN). I am wondering if there is any way to do this using something such as PHP or JavaScript?
Here is a picture of a working example of my loan calculator:
Here is my full page code for the loan calculator:
<!doctype html>
<html>
<head>
<style>
body {
font-family:arial,verdana,sans-serif;
}
img a {
border:none;
}
img {
border:none;
}
.bback {
text-align:center;
width:100%;
}
#image {
width:84px;
height:41px;
}
#stretchtable {
width:60%;
max-width:500px;
min-width:200px;
}
.fontwhite {
color:white;
background-color:black;
border:4px grey solid;
padding:5px;
text-align:left;
}
</style>
<meta charset="utf-8">
<title> ::: Loan Calculator</title>
</head>
<body bgcolor="#102540">
<script language="JavaScript">
<!--
function showpay() {
if ((document.calc.loan.value == null || document.calc.loan.value.length == 0) ||
(document.calc.months.value == null || document.calc.months.value.length == 0)
||
(document.calc.rate.value == null || document.calc.rate.value.length == 0))
{ document.calc.pay.value = "Incomplete data";
}
else
{
var princ = document.calc.loan.value;
princ = princ.replace(',','');
var myfloat = parseFloat(princ);
var term = document.calc.months.value;
term = term.replace(',','');
var myfloat1 = parseFloat(term);
var intr = document.calc.rate.value / 1200;
intr = intr.replace(',','');
var myfloat2 = parseFloat(intr);
document.calc.pay.value = (myfloat * myfloat2 / (1 - (Math.pow(1/(1 + myfloat2), myfloat1)))).toFixed(2)
}
// payment = principle * monthly interest/(1 - (1/(1+MonthlyInterest)*Months))
}
// -->
</script>
<script>
function trimDP(x, dp) {
x = parseFloat(x);
if (dp === 0)
return Math.floor(x).toString();
dp = Math.pow(10, dp || 2);
return (Math.floor((x) * dp) / dp).toString();
}
window.addEventListener('load', function () {
var nodes = document.querySelectorAll('.dp2'), i;
function press(e) {
var s = String.fromCharCode(e.keyCode);
if (s === '.')
if (this.value.indexOf('.') === -1)
return; // permit typing `.`
this.value = trimDP(this.value + s);
e.preventDefault();
};
function change() {
this.value = trimDP(this.value);
}
for (i = 0; i < nodes.length; ++i) {
nodes[i].addEventListener('keypress', press);
nodes[i].addEventListener('change', change);
}
});
</script>
<div class="bback">
<h1 style="color:white;font-size:16px;">G.B.M. Trailer Service Ltd. Loan Calculator</h1>
<a href="index.html">
<img src="images/backbutton.png" alt="Back Button" id="image" title="Back"></a><br /><br />
<center>
<div class="fontwhite" style="width:60%;">
The results of this loan payment calculator are for comparison purposes only.
They will be a close approximation of actual loan
repayments if available at the terms entered, from a financial institution. This
is being
provided for you to plan your next loan application. To use, enter values
for the
Loan Amount, Number of Months for Loan, and the Interest Rate (e.g.
7.25), and
click the Calculate button. Clicking the Reset button will clear entered
values.
</div>
</center>
</div>
<p>
<center>
<form name=calc method=POST>
<div style="color:white; font-weight:bold; border:4px grey outset; padding:0px; margin:0px;" id="stretchtable">
<table width="100%" border="1" style="border:1px outset grey">
<tr><th bgcolor="black" width=50%><font color=white>Description</font></th>
<th bgcolor="black" width=50%><font color=white>Data Entry</font></th></tr>
<tr><td bgcolor="black">Loan Amount</td><td bgcolor="black" align=center><input
type=text name=loan
size=10 class="dp2" onkeyup="format(this)"></td></tr>
<tr><td bgcolor="black">Loan Length in Months</td><td bgcolor="black"
align=center><input type=text
name=months size=10 onkeyup="format(this)"></td></tr>
<tr><td bgcolor="black">Interest Rate</td><td bgcolor="black" align=center><input
type=text name=rate
size=10 onkeyup="format(this)"></td></tr>
<tr><td bgcolor="black">Monthly Payment</td><td bgcolor="black"
align=center><em>Calculated</em> <input
type=text name=pay size=10 class="dp2" onkeyup="format(this)"></td></tr>
<tr><td bgcolor="black"align=center><input type=button onClick='showpay()'
value=Calculate></td><td bgcolor="black" align=center><input type=reset
value=Reset></td></tr>
</table>
</div>
</form>
<div style="width:60%;">
<font size=2 color=white>Enter only numeric values (no commas), using decimal points
where needed.<br>
Non-numeric values will cause errors.</font>
</center>
</div>
<p align="center"><font face="arial" size="-2">This free script provided by</font><br>
<font face="arial, helvetica" size="-2"><a href="http://javascriptkit.com">JavaScript
Kit</a></font></p>
</body>
</html>
I am looking for a solution to my problem, as I am not experienced with this type of code. Suggestions may only get me so far.
Thank you for any help. All help is greatly appreciated.
Replace this:
var intr = document.calc.rate.value / 1200;
with this
var intr = (parseFloat(document.calc.rate.value) / 1200).toString()
For the adding commas bit, replace this:
document.calc.pay.value = (princ * intr / (1 - (Math.pow(1/(1 + intr), term)))).toFixed(2)
with this
document.calc.pay.value = (princ * intr / (1 - (Math.pow(1/(1 + intr), term)))).toFixed(2).toLocaleString()
there are other ways to do it, but this seems like the fastest way without introducing more functions. JavaScript gives us toLocaleString which should be your most flexible option.
Before calculation simply use .replace(',','') to remove the commas. Then you need to cast it to to a float by using parseFloat(). Then when you go to display the numbers you can reformat it with commas if you would like.
var mystring = '10,000.12';
mystring = mystring.replace(',','');
var myfloat = parseFloat(mystring);
For adding the commas back in you can do something like this:
How to print a number with commas as thousands separators in JavaScript
From that answer:
function numberWithCommas(x) {
var parts = x.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
}