How can I prevent my function from running on every click? - javascript

I'm trying to make a dynamic drop down list using HTML and JavaScript, but every time I click on the drop down I get a new set of duplicate values. How can I prevent this from happening? I would prefer to stick to vanilla JS and html
function yearsArray(num) {
let years=document.getElementById("years")
let year=[...Array(num+1).keys()]
year.shift()
year.shift()
year.forEach(element => {
switch (element) {
case 1:
years.add(new Option(element,element,true))
break;
default:
years.add(new Option(element,element,false))
break;
}
})
}
body{
font-family: Arial, Helvetica, sans-serif;
}
h1{
color: gray;
}
<!DOCTYPE html>
<head>
<script src="script.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<title>Simple Interest Calculator</title>
<body>
<div class="maindiv">
<h1>Simple Interest Calculator</h1>
<form>
<label for="principal">Amount</label>
<input type="number" name="principal" id="principal"> <br/>
<label for="rate">Interest Rate</label>
<input type="range" id="rate" name="rate" min="0" max="20" step=".25">
<span id="rate_val">10.25%</span> <br/>
<label for="years">No. of Years </label>
<select id="years" name="years" onclick="yearsArray(20)">
<option selected value="1">1</option>
</select><br/>
<!-- Interest : <span id="result"></span><br/> -->
<button type="submit">Compute Interest</button>
</form>
</div>
</body>
</html>

Just run that function once on page load:
(You could of course just create the options using markup)
function yearsArray(num) {
let years = document.getElementById("years")
let year = [...Array(num + 1).keys()]
year.shift()
year.shift()
year.forEach(element => {
switch (element) {
case 1:
years.add(new Option(element, element, true))
break;
default:
years.add(new Option(element, element, false))
break;
}
})
}
yearsArray(20); //<---------- This runs the function on page load
body {
font-family: Arial, Helvetica, sans-serif;
}
h1 {
color: gray;
}
<!DOCTYPE html>
<head>
<script src="script.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<title>Simple Interest Calculator</title>
<body>
<div class="maindiv">
<h1>Simple Interest Calculator</h1>
<form>
<label for="principal">Amount</label>
<input type="number" name="principal" id="principal"> <br/>
<label for="rate">Interest Rate</label>
<input type="range" id="rate" name="rate" min="0" max="20" step=".25">
<span id="rate_val">10.25%</span> <br/>
<label for="years">No. of Years </label>
<select id="years" name="years">
<option selected value="1">1</option>
</select><br/>
<!-- Interest : <span id="result"></span><br/> -->
<button type="submit">Compute Interest</button>
</form>
</div>
</body>
</html>

Figured it out. added the javascript function to the body tag
<body onload=yearsArray(20)></body>

Related

Problems on the generated value of the qr code into a input field using JavaScript

JavaScript codes and HTML codes
I'm trying to put a generated value of the qr code a input text to be save in my SQLite database can't pust the darn value of the qr code
var resultDiv;
document.addEventListener("deviceready", init, false);
function init() {
document.querySelector("#startScan").
addEventListener("touchend", startScan, false);
resultDiv = document.querySelector("#results");//works in <p id="results"></p>
resultDiv = document.querySelector('#text4');//wont work at all <input id="text4" type="text" placeholder="Book Info"/>
}
function startScan() {
cordova.plugins.barcodeScanner.scan(
function (result) {
var s = result.text.split('|');
result.format;
result.cancelled;
resultDiv.innerHTML = s;
},
function (error) {
alert("Scanning failed: " + error);
}
);
}
JavaScript codes and HTML codes
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>qrBorrowers</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<script type="text/javascript" src="cordova.js"></script>
<nav>
<div class="topnav">
Add
Borrow
Return
QR code
</div>
</nav>
<Label>
<h1> Borrow a Book </h1>
</Label>
<div class="borrow">
<input id="text1" type="text" placeholder="Borrower Number" onfocus="this.value=''"/>
<input id="text2" type="text" placeholder="Borrower Last Name" onfocus="this.value=''" />
<input id="text3" type="text" placeholder="Borrower First Name" onfocus="this.value=''" />
<input id="text4" type="text" placeholder="Book Info"/>
<input id="text6" type="date" placeholder="Date Borrowed" />
<br>
</div>
<div class="borrow">
<p id="results"></p>
<button id="startScan">Start Scan</button>
<button id="savedb">Save </button>
</div>
<script type="text/javascript" src="js/scanQR.js"></script>
</body>
</html>
With inner HTML it will not going to save your generated QR code to input box. You need to change the innerHTML to value to save the value in input box such that you can use that when form submit as value to save in database.
var resultDiv;
document.addEventListener("deviceready", init, false);
function init() {
document.querySelector("#startScan").
addEventListener("touchend", startScan, false);
resultDiv = document.querySelector("#results");//works in <p id="results"></p>
resultDiv = document.querySelector('#text4');//wont work at all <input id="text4" type="text" placeholder="Book Info"/>
}
function startScan() {
cordova.plugins.barcodeScanner.scan(
function (result) {
var s = result.text.split('|');
result.format;
result.cancelled;
resultDiv.value = s;
},
function (error) {
alert("Scanning failed: " + error);
}
);
}
JavaScript codes and HTML codes
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>qrBorrowers</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<script type="text/javascript" src="cordova.js"></script>
<nav>
<div class="topnav">
Add
Borrow
Return
QR code
</div>
</nav>
<Label>
<h1> Borrow a Book </h1>
</Label>
<div class="borrow">
<input id="text1" type="text" placeholder="Borrower Number" onfocus="this.value=''"/>
<input id="text2" type="text" placeholder="Borrower Last Name" onfocus="this.value=''" />
<input id="text3" type="text" placeholder="Borrower First Name" onfocus="this.value=''" />
<input id="text4" type="text" placeholder="Book Info"/>
<input id="text6" type="date" placeholder="Date Borrowed" />
<br>
</div>
<div class="borrow">
<p id="results"></p>
<button id="startScan">Start Scan</button>
<button id="savedb">Save </button>
</div>
<script type="text/javascript" src="js/scanQR.js"></script>
</body>
</html>
To save the value in input box should not use "resultDiv.innerHTML = s;"
Rather you should use "resultDiv.value = s" which will save your code to input box which you can use to save in SQLite Database.

How to add error Handling to check if the inputs are numbers in a separate function

I am looking to have the inputs only numbers and if its anything else then it will alert that you typed in a letter and it has to be in a different function. Also, it has to be in vanilla javascript and it is for a project and has to have 3 running functions that's why it has to be in a separate function.Thanks!
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
<meta charset="utf-8">
<title>Tip Calc.</title>
<style>
html,body{
width:100%;
height:100%;
}
body{
margin:0px;
overflow-x:hidden;
background-color: #f9f8f4 !important
}
p{
font-size: 18px !important;
font-family: 'Raleway', sans-serif;
}
h1,h2,h3{
font-family: 'Raleway', sans-serif;
}
</style>
</head>
<body>
<div class="container">
<br>
<h1 class="text-center">Tip Calculator</h1>
<br><br>
<div class="row">
<div class="col-lg-6">
<form>
<div class="form-group">
<label for="exampleInputEmail1">Total</label>
<input type="text" class="form-control" id="total" aria-describedby="emailHelp" placeholder="Enter Total Price">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Tip Percentage %</label>
<input type="text" class="form-control" id="percent" placeholder="Tip Percentage">
</div>
<button type="submit" class="btn btn-primary" id="btn">Submit</button>
</form>
</div>
<div class="col-lg-6">
<h2>Total Price:</h2><h3 id="totalprice"></h3>
</div>
</div>
</div>
<script>
window.addEventListener("DOMContentLoaded",init,false);
function init(){
document.getElementById("btn").addEventListener("click", getprice, false);
}//end init function
function getprice(e) {
e.preventDefault();
math();
// var totalpriceout = document.getElementById("totalprice").value = totalValue.toFixed(2);
}
function math(){
var numVal1 = Number(document.getElementById("total").value);
var numVal2 = Number(document.getElementById("percent").value) / 100;
var totalValue = numVal1 + (numVal1 * numVal2)
document.getElementById("totalprice").innerHTML = "$" + totalValue.toFixed(2);
}
</script>
</body>
</html>
The baseline of what you're looking for is parseFloat, i.e.
var foo = "abcdef"
var bar = "123456"
foo == parseFloat(foo)
->false
bar == parseFloat(bar)
->true
since this appears to be homework help I don't want to give too much away past that.
As stated here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat, parseFloat will return a floating point number parsed from the given value. If the value cannot be converted to a number, NaN is returned.
consider using Number.isNaN() in conjunction.
perhaps:
if (Number.isNaN(parseFloat(foo))) { //error handler } else { //regular action} –

Angular Controller not receiving values from ng-model

var app = angular.module("colorIt",[]);
app.controller("ColorCtrl",function() {
this.shape = '';
this.style = {
'border-color': '',
'background-color': '',
'border-width': '',
'border-style': ''
};
});
<!Doctype html>
<html data-ng-app="colorIt">
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="assets/css/app.css">
<link href="https://fonts.googleapis.com/css?family=Niconne|Quicksand:400,700" rel="stylesheet">
<title>Colorit</title>
</head>
<body>
<div id="user">
<h1>Colorit</h1>
<div id="inputs">
<label for="shapes">Shape</label>
<select class="shapes" name="shapes" ng-model="shape">
<option value="">Select Shape</option>
<option value="square">Square</option>
<option value="circle">Circle</option>
</select>
<label for="background-color">Background Color</label>
<input type="color" name="background-color" ng-model="style['background-color']">
<label for="border-style">Border Style</label>
<input type="text" name="border-style" value="solid" ng-model="style['border-style']" placeholder="solid dashed dotted inset">
<label for="border-width">Border Width</label>
<input type="text" name="border-width" value="2px" ng-model="style['border-width']" placeholder="2px 4px 2px 4px">
<label for="border-color">Border Color</label>
<input type="color" name="border-color" ng-model="style['border-color']" ng-init="#000" value="#000000">
<label for="shadow">Box Shadow</label>
<input type="text" name="shadow" ng-model="shadow" value="5px 5px 10px" placeholder="5px 5px 10px">
<label for="shadow-color">Shadow Color</label>
<input type="color" ng-model=color name="shadow-color" value="#000">
</div>
</div>
<div id="display" ng-controller="ColorCtrl as color">
<div ng-class="{{color.shape}}" ng-style="{{color.style}}">
{{color.style['border-color']}},{{color.style['background-color']}},{{color.style['border-width']}}
</div>
</div>
<script src="assets/js/colorit.js" charset="utf-8"></script>
</body>
</html>
The controller is not storing values from the ng-model. Initially I had built this app using only directives, which was working, but then I had to set default values of various inputs, so I am using a controller.
Also, I am getting this error in my console
Error: [$parse:lexerr] http://errors.angularjs.org/1.6.0/$parse/lexerr?p0=Unexpected%20nextharacter%20&p1=s%200-0%20%5B%23%5D&p2=%23000
at https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js:6:425
at pc.throwError (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js:221:149)
at pc.lex (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js:218:369)
at r.ast (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js:225:175)
at Cd.compile (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js:235:100)
at qc.parse (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js:260:332)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js:131:115
at m.$eval (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js:147:65)
at Object.pre (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js:284:350)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js:16:71
Move ng-controller="ColorCtrl as color" to the body tag and use controllerAs reference color in your bindings:
ng-model="color.style['border-width']
etc. for all ngModels.

Issues getting the secondary drop down to validate when using onchange

I am trying to get the selected drop down printerType to alert user when the printer type value is not selected but only when the user selects request the printertype box shows up. The issue I have is that it doesn't alert the user that it is not filled. The others work fine. I hope this is understanding may be little confusing. the JavaScript code is at the bottom.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Systems Request</title>
<!--bootstrap-->
<link href="Assets/css/bootstrap.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="../Assets/javascript/html5shiv.min.js"></script>
<script src="../Assets/javascript/respond.min.js"></script>
<![endif]-->
<!--custom css-->
<link rel="stylesheet" type="text/css" media="all" href="Assets/css/style.css">
<link rel="stylesheet" type="text/css" media="all" href="Assets/css/responsive.css">
<script src="Assets/Javascript/jquery-1.11.1.min.js" type=
"text/javascript"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="Assets/javascript/bootstrap.js"></script>
<script src="Assets/Javascript/textboxname_autocomplete.js" type=
"text/javascript"></script>
<style type="text/css">
.dropdown{
width: 292px;
height: 45px;
font-size: 16px;
margin-left: 30px;
margin-bottom: 10px;
background-color: pink;
}
</style>
</head>
<body style="background-image: url('../Systems/Assets/images/background.jpg')">
<?php include("includes/createHeader.php");?>
<section id="container">
<h2>Systems Request</h2>
<form name="systems" id="systems-form" action="Pages/InsertProcess.php" method="post"onsubmit="return formCheck(this);">
<div id="wrapping" class="clearfix">
<section id="aligned">
<label class="label">LanID</label><br><br>
<input type="text" name="lanId" id="lanId" autocomplete="off" tabindex="1" class="txtinput" >
<label class="label">Employee Name</label><br><br>
<input type="text" name="name" id="name" autocomplete="off" tabindex="1" class="txtinput">
<!--manager access db list info located in the includes folder-->
<label class="label">Manager</label><br><br>
<?php include("includes/accessDB_ManagerData.php");?>
<!--department dropdownlist located in the includes folder-->
<label class="label">Department</label><br><br>
<?php include("includes/departmentDropdownList.php");?>
<!--Request Issue list info located in the includes folder-->
<label class="label">Request Issue</label><br><br>
<!-- #start of Request Issues-->
*<select name ="request" id="request" onchange="if (this.selectedIndex==3){this.form['printerType'].style.visibility='visible'}else {this.form['printerType'].style.visibility='hidden'};">
<option value =""><?php echo ' Select Request Issue...'?></option>
<option value ="RESET CASE"><?php echo ' Reset Case'?></option>
<option value ="RESET WM PASSWORD"><?php echo " RESET WM PASSWORD"?></option>
<option value ="REPLACE TONER"><?php echo " REPLACE TONER"?></option>
<option value ="FIX PRINTER"><?php echo " FIX PRINTER"?></option>
<option value ="FIX DEVICES"><?php echo " FIX DEVICE"?></option>
<option value ="SAFETY HIGH REQUEST"><?php echo " SAFETY HIGH REQUEST"?></option>
<option value ="OTHER"><?php echo " OTHER"?></option>
</select><br>
<!-- #end of Request Issues-->*
***<select class="dropdown" style="visibility:hidden;" name="printerType" id="printerType" >
<option Value="">Please select Printer Type</option>
<option Value="FS 4200DN">Kyocera FS4200DN</option>
<option Value="FS 3040MFP">Kyocera FS3040MFP</option>
<option Value="Kyocera ">Kyocera FS1370DN </option>
<option Value="OKI MPS710C">OKI MPS710C</option>
<option Value="OKI MPS711C">OKI MPS711C</option>
<option Value="Sharp MX450N">Sharp MX450N</option>
</select>***
<br/>
<label class="label">Request Description </label><br><br>
<textarea name="request_comments" id="message" placeholder="Enter Description of Issue" tabindex="5" class="txtblock"></textarea>
<input type="submit" name="submit" id="submitbtn" class="btn btn-primary btn" tabindex="7" value="Submit">
<br style="clear:both;">
<?php #Hidden inputs for Status, tech comments, tech completed, tech completed date?>
<input name="status" type="hidden" value="RECEIVED">
<input name="comments" type="hidden" value="No Comment ">
<input name="compUser" type="hidden" value="Unassigned">
<input name="compDt" type="hidden" value="Not Completed">
</section>
</section>
</div>
</form>
</section>
<?php include("includes/footer.php");?>
<script src="Assets/Javascript/gen_validatorv4.js" type="text/javascript"></script>
</head>
<script type="text/javascript">
var frmvalidator = new Validator("systems");
if (document.getElementById('request').selectedIndex==3){
frmvalidator.addValidation("printerType","req","Please enter Printer Type");
}
else{
frmvalidator.addValidation("lanId","req","Please enter LanID");
frmvalidator.addValidation("request_comments","req","Please enter request comments");
}
</script>
</body>
</html>
I had to change a few things like getElementbByName to getElementById. also added a function called updateValidation to add to the onchange part of the selected box and added frmvalidator.clearAllValidations();to the function along with added the two other textboxes lanId and request_comments to the if statement.
<select name ="request" id="request" onchange=" if (this.selectedIndex==3){this.form.printerType.style.visibility='visible'} else {this.form.printerType.style.visibility='hidden'};updateValidation()">
<script type="text/javascript">
function updateValidation (){
frmvalidator.clearAllValidations();
if (document.getElementById('request').selectedIndex==3){
frmvalidator.addValidation("lanId","req","Please enter LanID");
frmvalidator.addValidation("printerType","req","Please enter Printer Type");
frmvalidator.addValidation("request_comments","req","Please enter request comments");
}
else{
frmvalidator.addValidation("lanId","req","Please enter LanID");
frmvalidator.addValidation("request_comments","req","Please enter request comments");
}
}
</script>

How to do calculations in HTML forms using JavaScript?

I am building a simple app that multiplies a number entered by the user by 5 and displays the result. Since, I am a beginner, I need some help with this.
Here's my HTML code:
<!DOCTYPE html>
<head>
<title>Area Calc</title>
<link rel='stylesheet' type='text/css' href='style.css'/>
<link href='http://fonts.googleapis.com/css?family=Titillium+Web' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Exo+2' rel='stylesheet' type='text/css'>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type='text/javascript' src='script.js'></script>
<head>
<body>
<div class="heading">Number Of Persons Calc</div>
<div style=" color: white; text-align:auto; width:400px; margin-right:auto; margin-left:auto; border:1px solid white; margin-top: 120px;">
<form method="" action="">
<input type="text" name="area" placeholder="Enter in square metres!" class="input" />
<input class="submit" type="submit" value="Submit" class="button" />
</form>
</div>
<body>
<html>
Can someone tell me what JavaScript/jQuery code could possibly take the value entered by the user from the text input element and multiply it by 5 and then display the result to the user? Please help me with this.
HTML
<input type="text" name="area" placeholder="Enter in square metres!" id="op" class="input" />
<input class="submit" type="button" value="Submit" class="button" onClick="mulBy()" />
SCRIPT
function mulBy(){
var op1=parseFloat(document.getElemntById("op").value);
val ans=op1*5;
alert(ans);
}
suppose you want to display the answer in a div having id "result":
<input type="text" name="area" placeholder="Enter in square metres!" class="input" />
<input class="submit button" type="submit" value="Submit" />
<div id="result"></div>
This div is placed just after the submit button. Now write the following code after the line:
<script type='text/javascript' src='script.js'></script>
$(document).ready(function(){
$(".submit ").click(function(){
$("#result").html(parseInt($(".input").val())*5);
return false;
});
});
Calculate in HTML without using Form and submit button
HTML
<input type="text" id="area" name="area" placeholder="Enter in square metres!"
class="input"/>
<br/>
<div id="result"></div>
JqueryCode
$(document).ready(function(){
$("input#area").change(function(){
var input_box = $('#area').val();
if ( input_box != ''){
$("div#result").html(input_box*5);
}
else{
$("div#result").html("");
}
});
});
LiveDemo JsFiddle

Categories

Resources