Prompt User for Input but display Input on Form - javascript

Good Morning,
Does anyone know how to correct the code below? First, I prompt the user for the variables first and second but am failing to have them display on the form. Second, when the user clicks on the Determine the larger number button it is supposed to run the if and else if statement located under the function determineLarge(){ but it fails to run. My apologies as I am learning at the university to code this language. Thank you for the help.
<script>
function determineLarge(){
let first = prompt ("Enter the first number.");
first= document.myForm.first.value;
let second = prompt("Enter the second number.");
second =document.myForm.first.value;
first = parseFloat(first);
second = parseFloat(second);
let message = "";
if (first <0 || second <0){
message = "You can't use negative numbers.";
}
else if (first > second){
message = "The second number" + "(" + second + ")" + " is smaller.";
}
else if (second > first) {
message = "The first number" + "(" + first + ")" + " is smaller.";
}
else if (first == second || second==first){
message = "The first number" + "(" + first + ")" + " is smaller.";
}
document.getElementById("results").innerHTML = message;
}
</script>
</head>
<body>
<h1>Gary's Smaller of Two Numbers</h1>
<form name="myForm">
<p> Enter the first number</p>
<input type="number" name="first" value="" onclick="javascript:determineLarge();">
<p>Enter the second number</p>
<input type="number" name="second" value="" onclick="javascript:determineLarge();">
<button type="button" onclick="determineLarge();">Determine the larger number</button>
</form>
<div id="results"> </div>
</body>

I separated the getting of the values and processing of them into two functions.
I put the prompts in a while loop so you are forced to enter in a real value greater than zero.
Also you overwrite the first and second variables by keeping the variable name first ie: first = .... instead of document.myform.value == first etc..
first = -1;
second = -1;
function getValues(){
while(isNaN(first) || first == "" || first < 0){
first = prompt ("Enter the first number.");
}
while(isNaN(second) || second == "" || second < 0){
second = prompt ("Enter the second number.");
}
document.myForm.first.value = first;
document.myForm.second.value = second;
}
function determineLarge(){
let message = "";
if (first > second){
message = "The second number" + "(" + second + ")" + " is smaller.";
}
else if (second > first) {
message = "The first number" + "(" + first + ")" + " is smaller.";
}
else if (first == second || second==first){
message = "The first number" + "(" + first + ")" + " is smaller.";
}
document.getElementById("results").innerHTML = message;
}
<h1>Gary's Smaller of Two Numbers</h1>
<form name="myForm">
<p> Enter the first number</p>
<input type="number" name="first" value="" onclick="javascript:getValues();">
<p>Enter the second number</p>
<input type="number" name="second" value="" onclick="javascript:getValues();">
<button type="button" onclick="determineLarge();">Determine the larger number</button>
</form>
<div id="results"> </div>

I removed the prompt so that the inputs can be used. No need to call onClick on the text input.
<script>
function determineLarge(myForm) {
var first = myForm.first.value;
var second = myForm.second.value;
console.log(first, second)
first = parseFloat(first);
second = parseFloat(second);
let message = "";
if (first < 0 || second < 0) {
message = "You can't use negative numbers.";
} else if (first > second) {
message = "The second number" + "(" + second + ")" + " is smaller.";
} else if (second > first) {
message = "The first number" + "(" + first + ")" + " is smaller.";
} else if (first == second || second == first) {
message = "The first number" + "(" + first + ")" + " is smaller.";
}
document.getElementById("results").innerHTML = message;
}
</script>
</head>
<body>
<h1>Gary's Smaller of Two Numbers</h1>
<form name="myForm">
<p> Enter the first number</p>
<input type="number" name="first" value="">
<p>Enter the second number</p>
<input type="number" name="second" value="">
<button type="button" onclick="determineLarge(this.form);">Determine the larger number</button>
</form>
<div id="results"> </div>
</body>

Related

How to print javascript while loop result in html textarea?

Prints '2 x 10 = 20' but not the whole table when the input is 2. I tried various means. But the result is same.
No error. Just like to print the whole multiplication table.
function loop() {
var i = 1;
var x = document.getElementById("num").value;
//document.getElementById("result").value = result;
while (i <= 10) {
document.getElementById("result").value = x + " x " + i + " = " + i * x;
i++;
}
}
<h1>While loop: </h1>
<p>The while loop keeps repeating an action until an associated condition returns false.</p>
<img src="images/loop.jpg" /><br/>
<img src="images/loop2.jpg" /><br/>
<body>
<p>JavaScripts Runs:</p>
<script src="while_1loop.js">
</script><br/> What number table would you like to have?<input type="number" name="" id="num" /><br>
<button type="button" onclick="loop()" ;>Start</button><br>
<textarea rows="12" cols="15" id="result" readonly>
</textarea><br/>
You are always changing the value of 'result' rather than adding to it:
function loop() {
var i = 1;
var x = document.getElementById("num").value;
//document.getElementById("result").value = result;
while (i <= 10) {
var result = document.getElementById("result");
var sum = document.createTextNode(x + " x " + i + " = " + i * x + "\n");
result.appendChild(sum);
i++;
}
}
<h1>While loop: </h1>
<p>The while loop keeps repeating an action until an associated condition returns false.</p>
<img src="images/loop.jpg" /><br/>
<img src="images/loop2.jpg" /><br/>
<body>
<p>JavaScripts Runs:</p>
<script src="while_1loop.js">
</script><br/> What number table would you like to have?<input type="number" name="" id="num" /><br>
<button type="button" onclick="loop()" ;>Start</button><br>
<textarea rows="12" cols="15" id="result" readonly>
</textarea><br/>
If I understand what you mean,
You rewrite whole textarea with this code:
document.getElementById("result").value = x + " x " + i + " = " + i * x;
but you need add new result after older results. Something like this:
var oldValue = document.getElementById("result").value;
var result = x + " x " + i + " = " + i * x;
document.getElementById("result").value = oldValue + '\n' + result;

Consume an endpoint using optional parameters in angularjs

I have a form with 2 sections. From each section, at least one value must be selected.
I know how to pass compulsory parameters but passing the appropriate parameters based on user selection is what I am not sure of.
Any ideas please?
Template plunker here
<form>
<div>
<label>Section 1</label></br>
<input type="checkbox" name="chkBox1" value="chkBox1">chkBox1<br>
<input type="checkbox" name="chkBox2" value="chkBox2">chkBox2<br>
<input type="checkbox" name="chkBox3" value="chkBox3">chkBox3<br>
</div>
<div>
<label>Section 2</label>
<div>
Optional 1:
<input type="text" name="fname" value="fname" />
</div>
<div>
Optional 2:
<input type="text" name="lname" value="lname" />
</div>
</div>
<button ng-click="getAll()">Get result</button>
</form>
Controller function
$scope.getAll = function() {
return $http.get('/api/testing?chbox1='+ 1 +'&chbox3=' + 1
+'&chbox2=' + 0 +'&optional1=' + fname +'&optional2=' + lname);
},
You can concat your URL depending of fname & lname defined or not:
return $http.get('/api/testing?chbox=' + 1 + '&chbox3=' + 1 + '&chbox2=' + 0 + ((fname !== undefined) ? '&optional1=' + fname : '') + ((lname !== undefined) ? '&optional2=' + lname : ''));
},
I used ternary conditions for writing it faster, but you can use multiple conditions for this case too:
$scope.getAll = function(){
var url;
if (fname !== undefined && lname !== undefined)
url = '/api/testing?chbox1='+ 1 +'&chbox3=' + 1 +'&chbox2=' + 0 +'&optional1=' + fname +'&optional2=' + lname;
else
if (fname !== undefined)
url = '/api/testing?chbox1='+ 1 +'&chbox3=' + 1 +'&chbox2=' + 0 +'&optional1=' + fname;
if (lname !== undefined)
url = '/api/testing?chbox1='+ 1 +'&chbox3=' + 1 +'&chbox2=' + 0 +'&optional2=' + lname;
}
Second option is less elegant!

Increment Serial Numbers and calculate - javascript

Our company has a client that requires a specific checksum on their bar codes. I've come up with the following which allows the user to enter the distributor part number, our part number and our serial number. Right now, when you click save, it will calculate correctly for the bar code with the checksum. NOW, we have added a quantity box so that we can print x number of barcodes with our serial number incrementing by 1. (i.e. 1st serial number is 000001, next will be 000002 and so on). What I've been trying to do for the last week is alter this code so the user can input the part numbers and sn, and it will calculate each bar code up to the quantity.
This is what we would like to have:
If user enters part numbers, first serial number and quantity then clicks "Save" this should be the result. At present, this can only be achieved by entering each serial number and clicking save
*note: while the quantity can be entered, the actual value has not been used in my code...yet
So, to achieve this, I need to find a way to increment the serial numbers without dropping off the leading zeros but maintaining the length of qty.length.
I also need to figure out how to loop each new serial number through with part numbers to get the correct checksum for the bar code. After a week of staring at this, I'm hoping some fresh and experienced eyes can assist. Here is my code.
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Capture Form Fields to CSV</title>
<script type="text/javascript">
<!--
function saveValues() {
var frm = document.form1;
var str = frm.text1.value + frm.text2.value + frm.text3.value;
var dpn = frm.text1.value;
var wpn = frm.text2.value;
var wsn = frm.text3.value;
var strArray = str.split("");
var calcArray = strArray;
var total =0;
for (var i = 0; i < str.length; i++)
strArray[i] = strArray[i].charCodeAt(0);
for (var i = 0; i < strArray.length; i++){
if (strArray[i] >= 65 && strArray[i] <= 90){
calcArray[i] = (strArray[i] - 64) * (i+1)
}
else if (strArray[i] >=97 && strArray[i] <=122) {
calcArray[i] = (strArray[i] - 96) * (i+1)
}
else if (strArray[i] >=48 && strArray[i] <=57) {
calcArray[i] = (strArray[i] - 48) * (i+1)
}
else {
calcArray[i] = 1 * (i+1)
}
}
for (var i in calcArray){
total += calcArray[i];}
var mod2 = str.length - (2*(Math.floor(str.length/2)));
var mod10 = (total + mod2) - (10*(Math.floor((total + mod2)/10))) ;
var chk = mod10;
var record = ""
+ dpn + "," + wpn + "," + wsn + "," +dpn + "~" + wpn + "~" + wsn + "~" + chk + "\n";
frm.textarea1.value += record;
}
function clearText() {
document.form1.textarea1.value = "";P
form1.text1.value = "";
form1.text2.value = "";
form1.text3.value = "";
}
function csvSave() {
var a = document.createElement('a');
with (a) {
href='data:text/csv;base64,' + btoa(document.getElementById('textarea1').value);
download='csvfile.csv';
}
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
//-->
</script>
</head>
<body>
<h1>Capture Form Fields to CSV</h1>
<form name="form1" >
<p>
Distributor Part Number: <input name="text1" type="text" value="GDM1301" /><br />
Our Part Number: <input name="text2" type="text" value="PCBDM160"/><br />
Our Serial Number: <input name="text3" type="text" value="000001"/><br />
Label Quantity: <input name="qty" type="text" value="3"/>
</p>
<p>
<input name="save" type="button" value="Save"
onclick="saveValues(); return false"/>
 
<input name="clear" type="button" value="Clear"
onclick="clearText(); return false"/>
<button onclick="csvSave()">CSV</button>
</p>
<p>
<i>Click 'Save' to add content</i><br />
<textarea id="textarea1" cols="80" rows="20"></textarea>
</p>
</form>
</body>
</html>

How can I get input value to work in Javascript

I am learning Javascript and trying to create something today. I have a text box, submit button and a hidden p tag called "demo". I want user to enter either number or text. If the user enter number it will then do one thing and if user text it will do another thing. Please see the code (any input will help...):
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Practice.aspx.cs" Inherits="Javascript.Javascript.Practice" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script>
function takeAction(){
var x = document.getElementById("textId").value;
// var y = document.getElementById("demo").innerHTML=("You entered "+x + ".");
if (x == Number) {
function numberFunction() {
switch (x) {
case 1:
document.getElementById("demo").innerHTML = ("You entered " + x + " and your number is 1.");
break;
case 2:
document.getElementById("demo").innerHTML = ("You entered " + x + " and your number is 2.");
break;
default:
document.getElementById("demo").innerHTML = ("You entered " + x + " and your number is not between 1 & 2.");
break;
}
}
if (x == Text) {
function textFunction() {
switch (x) {
case "John":
document.getElementById("demo").innerHTML = ("You are " + x + " and you are number 1 position.");
break;
case "Chris":
document.getElementById("demo").innerHTML = ("You are " + x + " and you are number 2 position.");
break;
default:
document.getElementById("demo").innerHTML = ("You are " + x + " and you are number not a member.");
break;
}
}
}
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<label>Please enter something: </label>
<input type="text" id="textId" />
<button id="btn" onclick="takeAction()">Submit</button><b />
<p id="demo"></p>
</div>
</form>
</body>
</html>
I guess you can use like this
HTML:
<form id="form1" >
<div>
<label>Please enter something: </label>
<input type="text" id="textId" />
<button id="btn" onclick="takeAction()">Submit</button><b />
<p id="demo"></p>
</div>
</form>
JS:
function takeAction() {
var x = document.getElementById('textId').value;
function numberFunction(number) {
var y = number;
switch (parseInt(y)) {
case 1:
document.getElementById('demo').innerHTML = ("You entered " + y + " and your number is 1.");
break;
case 2:
document.getElementById('demo').innerHTML = ("You entered " + y + " and your number is 2.");
break;
default:
document.getElementById('demo').innerHTML = ("You entered " + y + " and your number is not between 1 & 2.");
break;
}
}
function textFunction(text) {
var y = text;
switch (y) {
case "John":
document.getElementById('demo').innerHTML = ("You are " + y + " and you are number 1 position.");
break;
case "Chris":
document.getElementById('demo').innerHTML = ("You are " + y + " and you are number 2 position.");
break;
default:
document.getElementById('demo').innerHTML = ("You are " + y + " and you are number not a member.");
break;
}
}
if (isNaN(x)) {
textFunction(x);
} else {
numberFunction(x);
}
}
Another way I have done it in the past
var validNumbers = "0123456789";
var number = true
for(var i = 0;i<x.length;i++){
character = x.charAt(i);
if (validNumbers.indexOf(character) == -1){
number = false;
}
}
if(number) {
//It is a number
}
else {
//It isn't a number
}
Here is where I got the code from I was trying to do a similar thing to you. (sorry about the lack of indentation):
<html>
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
var number = true;
var validNumbers = "0123456789";
var character;
function validateForm() {
var result = true;
var msg="";
if (document.ExamEntry.name.value=="") {
msg+="You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if (document.ExamEntry.subject.value=="") {
msg+="You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
number = true
for(var i = 0;i<document.ExamEntry.examNumber.value.length;i++){
character = document.ExamEntry.examNumber.value.charAt(i);
if (validNumbers.indexOf(character) == -1){
number = false;
}
}
if (document.ExamEntry.examNumber.value.length != 4||number==false){
msg+="You must enter your examination number correctly \n";
document.ExamEntry.examNumber.focus();
document.getElementById('examNumber').style.color="red";
result = false;
}
if(msg==""){
return result;
}
{
alert(msg)
return result;
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="examNumber">Examination Number</td>
<td><input type="text" name="examNumber" /></td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" onclick="return validateForm();" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>

JavaScript For Loop Round Form Input Fields

I'm currently working on creating an expenses form and am writing a function to validate the entered data.
I allow for 6 expense amounts to be entered and a description on each and onClick of the submit button I am trying to write a for loop that will loop round the amount fields, check if they are numeric and, if they are, then check to ensure a description has been entered.
The form basically looks like:
<form action="##" name="myForm" id="myForm" method="post">
<input type="text" name="otherExpenseDesc1" id="otherExpenseDesc1">
<input type="text" name="otherExpenseAmount1" id="otherExpenseAmount1">
<input type="text" name="otherExpenseDesc2" id="otherExpenseDesc2">
<input type="text" name="otherExpenseAmount2" id="otherExpenseAmount2">
<input type="text" name="otherExpenseDesc3" id="otherExpenseDesc3">
<input type="text" name="otherExpenseAmount3" id="otherExpenseAmount3">
<input type="text" name="otherExpenseDesc4" id="otherExpenseDesc4">
<input type="text" name="otherExpenseAmount4" id="otherExpenseAmount4">
<input type="text" name="otherExpenseDesc5" id="otherExpenseDesc5">
<input type="text" name="otherExpenseAmount5" id="otherExpenseAmount5">
<input type="text" name="otherExpenseDesc6" id="otherExpenseDesc6">
<input type="text" name="otherExpenseAmount6" id="otherExpenseAmount6">
<input type="submit" name="formSubmitBtn" value="SUBMIT" onClick="checkForm();">
</form>
And the javascript I have at the moment is:
function checkForm() {
var errMsg = "";
var otherExpense1 = document.getElementById('otherExpenseAmount1').value;
var otherExpenseDesc1 = document.getElementById('otherExpenseDesc1').value;
var otherExpense2 = document.getElementById('otherExpenseAmount2').value;
var otherExpenseDesc2 = document.getElementById('otherExpenseDesc2').value;
var otherExpense3 = document.getElementById('otherExpenseAmount3').value;
var otherExpenseDesc3 = document.getElementById('otherExpenseDesc3').value;
var otherExpense4 = document.getElementById('otherExpenseAmount4').value;
var otherExpenseDesc4 = document.getElementById('otherExpenseDesc4').value;
var otherExpense5 = document.getElementById('otherExpenseAmount5').value;
var otherExpenseDesc5 = document.getElementById('otherExpenseDesc5').value;
var otherExpense6 = document.getElementById('otherExpenseAmount6').value;
var otherExpenseDesc6 = document.getElementById('otherExpenseDesc6').value;
for (i=1; i<7; i++) {
expenseNo = 'otherExpense' + i;
expenseDescNo = 'otherExpenseDesc' + i;
if (expenseNo != "") {
if (isNaN(expenseNo)) {
alert(expenseNo + ' is not a number');
errMsg = errMsg + 'The amount must be a number.<br />';
document.getElementById('otherExpenseAmount' + i).style.border = '2px sold #990000';
} else {
alert('otherExpenseAmount' + i + ' is a number');
document.getElementById('otherExpenseAmount' + i).style.border = '2px sold #990000';
}
}
}
if (errMsg != "") {
showDialog('alert', 'OK', '', errMsg, '');
}
}
When I'm submitting the form with valuesin a couple of the fields it still displays an alert for each otherExpenseAmount item saying that it is not numeric, although it is, and the border style doesn't change.
Any idea where I'm going wrong?
You're trying to access a variable with a string. You should change your code to utilise arrays, something like this:
jsFiddle
function checkForm() {
var errMsg = "";
var otherExpense = [];
otherExpense.push(document.getElementById('otherExpenseAmount1').value);
otherExpense.push(document.getElementById('otherExpenseAmount2').value);
otherExpense.push(document.getElementById('otherExpenseAmount3').value);
otherExpense.push(document.getElementById('otherExpenseAmount4').value);
otherExpense.push(document.getElementById('otherExpenseAmount5').value);
otherExpense.push(document.getElementById('otherExpenseAmount6').value);
// 0-based index for arrays
for (i=0; i<6; i++) {
if (otherExpense[i] != "") {
if (isNaN(otherExpense[i])) {
alert('otherExpense ' + (i + 1) + ' is not a number (=' + otherExpense[i] + ')');
errMsg = errMsg + 'The amount must be a number.<br />';
document.getElementById('otherExpenseAmount' + (i + 1)).style.border = '2px sold #990000';
} else {
alert('otherExpenseAmount' + (i + 1) + ' is a number');
document.getElementById('otherExpenseAmount' + (i + 1)).style.border = '2px sold #990000';
}
}
}
if (errMsg != "") {
alert(errMsg);
//showDialog('alert', 'OK', '', errMsg, '');
}
return false;
}
Your problem is on these lines; you're setting the border to be the same, regardless of the condition (easy mistake to make).
if (isNaN(expenseNo)) {
alert(expenseNo + ' is not a number');
errMsg = errMsg + 'The amount must be a number.<br />';
document.getElementById('otherExpenseAmount' + i).style.border = '2px sold #990000';
// -----------------------------------------------------------------------------^^^^^^
} else {
alert('otherExpenseAmount' + i + ' is a number');
document.getElementById('otherExpenseAmount' + i).style.border = '2px sold #990000';
// -----------------------------------------------------------------------------^^^^^^
}
Suggestion
I hate to be that guy.
Have you considered adopting jQuery? It's perfectly designed for tasks such as this.
Utilising methods such as filter and simple selectors, it's easy to determine whether all inputs fulfil your requirements. Here's an example:
// select all inputs with a class of "number"
// then filter those inputs, selecting only those where the value is "not a number"
// if there is a length, i.e. more than 0 were found, alert a message
if ($('input.number').filter(function() { return isNaN(this.value); }).length) {
alert('Please ensure all numbers are valid');
}
This would obviously require you to make small amendments to your HTML, by adding the number class to the required elements, but it's a small sacrifice to make.
jsFiddle demo

Categories

Resources