I am getting this awful error when I run this typescript... It says I am passing in the wrong 'type' of argument... This is my first time using typescript, any help would be appreciated.
Here is the error:
Could not apply type 'number' to argument 1 which is of type 'HTMLElement'.
And here is my TS code:
class Offer {
quantity: number;
price: number;
client: string;
constructor (quantity: number, price: number, client: string) {
this.quantity = quantity;
this.price = price;
this.client = name;
}
getSelectedItem() {
var option = $('#ddown :selected').text();
}
}
class Bid {
quantity: number;
price: number;
client: string;
constructor (quantity: number, price: number, client: string) {
this.quantity = quantity;
this.price = price;
this.client = name;
}
getSelectedItem() {
var option = $('#ddown :selected').text();
}
}
function getBid() {
var x = document.getElementById("quantity");
var y = document.getElementById("price");
console.log(y);
var n = document.getElementById("name");
return new Bid(x, y, n);
// $("<tr><td>" + n.value + "</td><td>" + x.value + "X$" + y.value + "</td></tr>").appendTo("#table");
}
function getOffer() {
var x = document.getElementById("quantity");
var y = document.getElementById("price");
console.log(y);
var n = document.getElementById("name");
return new Offer(x, y, n);
// $("<tr><td>" + n.value + "</td><td></td><td>" + x.value + "X$" + y.value + "</td></tr>").appendTo("#table");
}
function append_bid(bid) {
alert("efff you");
$("<tr><td>" + bid.client + "</td><td>" + bid.quantity + "X$" + bid.price+ "</td></tr>").appendTo("#table");
}
function append_offer(offer) {
$("<tr><td>" + offer.client + "</td><td></td><td>" + offer.quantity + "X$" + offer.price + "</td></tr>").appendTo("#table");
}
var bids = [];
var offers = [];
$(document).ready(function(){
$("#submit").click(function(){
var msg = $("#ddown option:selected").text();
if (msg == 'Bid'){
bids.push(getBid());
alert(bids.peek);
append_bid(bids.peek);
console.log('here');
return false;
} else {
offers.push(getOffer());
console.log('whatever');
console.log(offers[0].price);
append_offer(offers.peek);
}
return false;
});
return false;
});
I suppose some HTML wouldn't hurt either...
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Make Dem Trades Boi</title>
</head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="class.js"></script>
<table id="table">
<tr>
<th>name</th>
<th>bids</th>
<th>offers</th>
</tr>
</table>
<select id="ddown">
<option selected="selected" value="bid">Bid</option>
<option value="offer">Offer</option>
</select>
<form id="form">
Quantity:<input id="quantity" type="number"><br>
Price:<input id="price" type="number"><br>
Name:<input id="name" type="string">
<input id="submit" type="submit" value="Buy">
</form>
</body>
</html>
In getOffer(), here:
return new Offer(x, y, n);
x is an element (and so are y and n). If you want x’s value as a Number, you can use +x.value (or Number(x.value), if you like to be explicit).
The constructor on Bid takes a number, another number and a string:
constructor (quantity: number, price: number, client: string)
You are passing a HTMLElement to each of these. To satisfy the types of the Bid constrcutor, you need to get the data out of each element and parse it, which is reasonably easy to do...
var x = +(<HTMLInputElement>document.getElementById("quantity")).value;
var y = +(<HTMLInputElement>document.getElementById("price")).value;
var n = (<HTMLInputElement>document.getElementById("name")).value;
return new Bid(x, y, n);
To break this answer down, you need to tell the compiler that the HTMLElement is in fact a HTMLInputElement and use the + operator to slacker parse the two numbers.
If you don't like the shorthand + operation, you can use:
var x = parseInt((<HTMLInputElement>document.getElementById("quantity")).value, 10);
var y = parseInt((<HTMLInputElement>document.getElementById("price")).value, 10);
var n = (<HTMLInputElement>document.getElementById("name")).value;
return new Bid(x, y, n);
Related
I'm trying to limit a function to run 5 times only with no success.
So the idea of the exercise is to create a function Person() that ask for a person's [name, surname and age] and ask for the user information 5 times.
My problem is to limit the function, at the moment i can add as many user's as i want not only 5.
<body>
<div class="container">
<div class="form-box">
<h1 id="title">Exercise</h1>
<form>
<div class="input-group" id="name-field">
<input type="text" placeholder="Nome" class='firstName' id="firstName-input">
<input type="text" placeholder="Apelido" class="lastName" id="lastName-input">
<input type="text" placeholder="Idade" class="age" id="age-input">
<div class="btn-field">
<button type="button" class="btn-adicionar" id="btn-adicionar" onclick="Person()">Add</button>
<button type="button" class="btn-mostrar" id="btn-mostrar" onclick="Show()">Show</button>
</div>
<p id="p"></p>
</div>
</form>
</div>
</div>
let Persona = [];
Persona.values = {
inputs: [],
labels: {
n: ' Name: ',
a: ' Surname: ',
i: ' Age: ',
},
};
function Adicionar() {
let firstName = document.getElementById('firstName-input').value;
let lastName = document.getElementById('lastName-input').value;
let age = document.getElementById('age-input').value;
Persona.values.inputs.push({
firstName: firstName,
lastName: lastName,
age: age,
});
}
function Show() {
let text = '';
for (var i = 0; i < Persona.values.inputs.length; i++) {
text += "<div class='outrow'>";
text += "<span class='lab'>" + Persona.values.labels.n + '</span>';
text +=
"<span class='outv'>" +
Persona.values.inputs[i].firstName +
'</span>';
text += "<span class='lab'>" + Persona.values.labels.a + '</span>';
text +=
"<span class='outv'>" +
Persona.values.inputs[i].lastName +
'</span>';
text += "<span class='lab'>" + Persona.values.labels.i + '</span>';
text +=
"<span class='outv'>" + Persona.values.inputs[i].age + '</span>';
text += '</div>';
}
let result = document.getElementById('p');
result.innerHTML = text;
}
I've tried to use an if statement but still have the same result.
function Person() {
let number = 0
if (number < 5) {
let firstName = document.getElementById('firstName-input').value;
let lastName = document.getElementById('lastName-input').value;
let age = document.getElementById('age-input').value;
Persona.values.inputs.push({
firstName: firstName,
lastName: lastName,
age: age,
});
number++
}
}```
I think you don't need the counter variable at all, just check Persona.values.inputs.length.
function Person() {
if (Persona.values.inputs.length < 5) {
let firstName = document.getElementById('firstName-input').value;
let lastName = document.getElementById('lastName-input').value;
let age = document.getElementById('age-input').value;
Persona.values.inputs.push({
firstName: firstName,
lastName: lastName,
age: age,
});
}
}
You can also assign input values directly to the object and avoid creating unnecessary variables
function Person() {
if (Persona.values.inputs.length < 5) {
Persona.values.inputs.push({
firstName: document.getElementById('firstName-input').value,
lastName: document.getElementById('lastName-input').value,
age: document.getElementById('age-input').value,
});
}
}
You are adding your number counter variable inside the function that you want to limit, so everytime you call this function number will be reset to zero having no effect on the following condition. You actually want to declare your number variable as a global variable so it doesn't reset:
let number = 0
function Person() {
if(number < 5) {...}
number++
}
You can use a counter to track how many times the function has been called and return early if the limit has been reached. Here's an example:
let counter = 0;
function Person() {
if (counter === 5) {
return;
}
const name = prompt("Enter your name:");
const surname = prompt("Enter your surname:");
const age = prompt("Enter your age:");
console.log(`Name: ${name} Surname: ${surname} Age: ${age}`);
counter++;
}
This way, the function Person will stop running after the 5th time.
If for whatever reason you need to keep track of this on the function itself you can use a closure:
let Person = (function () {
let number = 1;
return function () {
if(number <= 5) {
console.log(`Called ${number} times`);
}
number++
}
})();
for (let i = 0; i < 100;i++) Person();
This defines a function along with a variable which is external to that function.
So I have this script that get 2 prices, and then finds the sum of it, and then finds a percentage of the sum depending on what state you choose, and then it adds the percentage. This script worked kind of fine without the if..else statement, but now that I added it, it won't work. Please help. Script:
<!DOCTYPE html>
<html>
<head>
<title>Test!!!!!</title>
<style>
</style>
</head>
<body>
<h2> Price checker </h2>
<input id = "x" type = "number" placeholder = "Price 1" >
<br><br><br>
<input id = "y" type = "number" placeholder = "Price 2" >
<br><br><br>
<select id="s">
<option value="NJ">NJ</option>
<option value="NY">NY</option>
<option value="PA">PA</option>
<option value="FL">FL</option>
</select>
<br><br><br>
<button onclick = "theFunction()">Calculate price</button>
<p id = "d"></p>
<script>
function theFunction() {
var x = document.getElementById("x").value
var y = document.getElementById("y").value
var z = +x + +y
var v = document.getElementById("s").value
var percentToGet;
var percent;
var final;
if v == "NJ" {
var percentToGet = 6.625;
var percent = (percentToGet / 100) * z;
var final = +percent + +z
} else if v == "NY" {
var percentToGet = 4;
var percent = (percentToGet / 100) * z;
var final = +percent + +z
}else if v == "PA" {
var percentToGet = 2;
var percent = (percentToGet / 100) * z;
var final = +percent + +z
} else if v == "FL" {
var percentToGet = 6;
var percent = (percentToGet / 100) * z;
var final = +percent + +z
}
document.getElementById("d").innerHTML = z + " " + final
}
</script>
</body>
</html>
Your if statement in the script tag ,is javascript code which is not having the parentheses.
It will be => if (v == "NJ") { }
Refer this MDN Web Docs to learn more if...else
Good evening. I am new to JavaScript and I need help with my mini-project and I have only one issue here and it is in the this.Add = function ().
It works properly when I enter a duplicate value from my list therefore it displays an alert that no dupes are allowed. But... when I enter a unique value, it only adds up the last element present (Wash the dishes) from myTasks list. instead of the one I recently entered and the list goes on adding the same ones. Did I just misplace something?
This is my final activity yet and I want to finish it to move to the next function. Thank you in advance.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Tasks CRUD</title>
<style>
#tasks{
display: none;
}
</style>
</head>
<body>
<center>
<form action="javascript:void(0);" method="POST" onsubmit="app.Add()">
<input type="text" id="add-task" placeholder="Add another card">
<input type="submit" value="Add">
</form>
<div id="tasks" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-task">
<input type="submit" value="Edit" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
<table>
<tr>
<th>Name</th>
</tr>
<tbody id="myTasks">
</tbody>
</table>
</center>
<script>
var app = new function() {
this.el = document.getElementById('myTasks');
this.myTasks = ['Clean the bathroom', 'Wash the dishes'];
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'task';
if (data) {
if (data > 1) {
name = 'Things To DO';
}
el.innerHTML = data + ' ' + name ;
} else {
el.innerHTML = 'No ' + name;
}
};
this.FetchAll = function() {
var data = '';
if (this.myTasks.length > 0) {
for (i = 0; i < this.myTasks.length; i++) {
data += '<tr>';
data += '<td>' + this.myTasks[i] + '</td>';
data += '<td><button onclick="app.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="app.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(this.myTasks.length);
return this.el.innerHTML = data;
};
this.Add = function () {
el = document.getElementById('add-task');
// Get the value
var task = el.value;
if (task ) {
for(task of this.myTasks)
{
var ctr = 0;
if(document.getElementById("add-task").value == task){
ctr = 1;
break;
}
}
if(ctr == 1)
{
window.alert("Duplicates not allowed.");
}else{
// Add the new value
this.myTasks.push(task.trim());
// Reset input value
el.value = '';
// Dislay the new list
this.FetchAll();
}
}
};
this.Edit = function (item) {
var el = document.getElementById('edit-task');
// Display value in the field
el.value = this.myTasks[item];
// Display fields
document.getElementById('tasks').style.display = 'block';
self = this;
document.getElementById('saveEdit').onsubmit = function() {
// Get value
var task = el.value;
if (task) {
// Edit value
self.myTasks.splice(item, 1, task.trim());
// Display the new list
self.FetchAll();
// Hide fields
CloseInput();
}
}
};
this.Delete = function (item) {
// Delete the current row
this.myTasks.splice(item, 1);
// Display the new list
this.FetchAll();
};
}
app.FetchAll();
function CloseInput() {
document.getElementById('tasks').style.display = 'none';
}
</script>
</body>
</html>
In your for loop:
for (task of this.myTask) {
}
You are not declaring a new task variable, but instead assigning to the outer task variable, hence the repeated addition of tasks already in your list.
You can declare a new variable in the for scope like so:
for (const task of this.myTask) {
}
Your HTML as it is.
And your Javascript goes like below. You have a bug while checking if the task already exists in the array. As you're comparing string value either use simple for loop with triple equals or do as i have attached below.
var app = new function() {
this.el = document.getElementById('myTasks');
this.myTasks = ['Clean the bathroom', 'Wash the dishes'];
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'task';
if (data) {
if (data > 1) {
name = 'Things To DO';
}
el.innerHTML = data + ' ' + name ;
} else {
el.innerHTML = 'No ' + name;
}
};
this.FetchAll = function() {
var data = '';
if (this.myTasks.length > 0) {
for (i = 0; i < this.myTasks.length; i++) {
data += '<tr>';
data += '<td>' + this.myTasks[i] + '</td>';
data += '<td><button onclick="app.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="app.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(this.myTasks.length);
console.log(this.myTasks.length);
return this.el.innerHTML = data;
};
this.Add = function () {
el = document.getElementById('add-task');
// Get the value
var task = el.value;
console.log(task);
if (task ){
var arrayContainsTask = (this.myTasks.indexOf(task) > -1);
if(arrayContainsTask == true){
window.alert("Duplicates not allowed.");
}else{
// Add the new value
this.myTasks.push(task);
// Reset input value
el.value = '';
}
// Dislay the new list
this.FetchAll();
}
}
}
From the input on the HTML, the user inputs the employee name and a number of hours they worked. From here on the submit button it takes the information and stores it in the variables so that I can calculate how much their pay was. Now with this also comes the overtime pay. I thought this was on the right track but whenever I go back to my HTML it displays "undefined". Any suggestions?
//Global Variables
var employeeName = document.getElementById("name").value;
var employeeHours = document.getElementById("hours").value;
function paySalary() {
if (employeeHours <= 40) {
var regtime = 11.00 * employeeHours;
var overtime = 0.00;
var salary = regtime;
} else if (employeeHours > 40) {
var regtime = (11.00 * 40);
var overtime = ((11.00 * 1.5) * (employeeHours - 40));
var salary = (regtime + overtime);
}
document.getElementById("results").innerHTML = "Employee Name: " + employeeName + " | Employee Gross Pay: " + salary;
}
//Event Listener to Submit
var submitButton = document.getElementById("submit");
if (submitButton.addEventListener) {
submitButton.addEventListener("click", paySalary, false);
} else if (submitButton.attachEvent) {
submitButton.attachEvent("onclick", paySalary);
}
Screenshot of output
Look at the scope of your salary variable, it's defined inside the if-else block. Make your salary variable accessible to document.getElementById() by declaring it in your function like this:
<html>
<script>
function paySalary() {
var employeeName = document.getElementById("name").value;
var employeeHours = document.getElementById("hours").value;
if (employeeHours <= 40) {
var regtime = 11.00 * employeeHours;
var overtime = 0.00;
var salary = regtime;
} else if (employeeHours > 40) {
var regtime = (11.00 * 40);
var overtime = ((11.00 * 1.5) * (employeeHours - 40));
var salary = (regtime + overtime);
}
document.getElementById("name").innerHTML = "Employee Name: " + employeeName;
document.getElementById("pay").innerHTML = "Employee Gross Pay: " + salary;
}
</script>
<body>
<input id="name" value="Kamesh Dashora"></input>
<input id="hours" value=40></input>
<br>
<span id="pay">0</span>
<br>
<button id="submit" onclick="paySalary()">Submit</button>
<body>
</html>
I want to be able to have a form that takes a 'deposit' or 'withdraw' and will add or subtract for a variable. Then, I would like to be able to put that variable in the webpage, and be able to keep it for a day or two. I do not know what is wrong with my code at this point.
<html>
<head>
<script language="JavaScript">
<!-- hide this script from old browsers
//Bank
var bank = 0;
var bank_name = "The Bank of Pacycephalosaurus";
var bank_interestPolicy = 0;
var bank_interestPolicy_interestAmount = 2;
var bank_ineterestPolicy_interest = function (amount) {
var interestGain = bank_contents_money / bank_interestPolicy_interestAmount;
var bank_contents_money = bank_contents_money + interestGain;
};
var bank_contents = 0;
var bank_contents_money = 0;
var bank_contents_items = "None";
var bank_withdrawAmount = "0";
var bank_depositAmount = "0";
var bank_withdraw = function (amount) {
//Check if there is money
if (bank_contents_money < amount) {
alert("Withdraw DENIED Insufficient Funds");
} else {
alert("Sufficient Funds ... Transfering Funds ...");
var transPlace = confirm("Transfer funds to " + wallet_name + "?");
if (transPlace === false) {
alert("Transfer Location Unknown :: 404 Not Found :: Please Try Again");
} else {
alert("Transfering Funds ... Transfer Succesful!");
form.bank_money.value = bank_contents_money - amount;
wallet_money = wallet_money + amount;
}
}
};
var bank_deposit = function (amount) {
//Check if there is money
if (wallet_money < amount) {
alert("Deposit DENIED Insufficient Funds");
} else {
alert("Sufficient Funds ... Transfering Funds ...");
var transPlace = confirm("Transfer funds to " + bank_name + "?");
if (transPlace === false) {
alert("Transfer Location Unknown :: 404 Not Found :: Please Try Again");
} else {
alert("Transfering Funds ... Transfer Succesful!");
alert("The Amount: " + amount);
form.bank_money.value = bank.contents_money + amount;
bank_contents_money = bank.contents_money + amount;
alert("The Amount: " + amount);
bank_opening(amount);
}
}
};
var bank_opening = function (money) {
alert("You have $" + bank_contents_money + " in your bank.");
$.cookie("bankMoney", money, {
expires: 1
});
alert($.cookie("example"));
};
var wallet = 0;
var wallet_name = "Wallet of You!";
var wallet_money = 0;
bank_opening();
// done hiding from old browsers -->
</script>
</head>
<body>
<form>
<h2>Bamk</h2>
Enter a number to withdraw or deposit:
<INPUT NAME="deposit" VALUE="0" MAXLENGTH="15" SIZE=15>
<p>
<INPUT NAME="depos" VALUE="Deposit" TYPE=BUTTON
onClick=bank_deposit(deposit.form)>
<p>
<p>
<INPUT NAME="withd" VALUE="Withdraw" TYPE=BUTTON
onClick=bank_withdraw(this.form)>
<p>
The amount in a bank is:
<INPUT NAME="bank_contents_money" READONLY SIZE=15>
</form>
</body>
</html>