Simple Javascript tax calculator - calculator

I am working on a tax calculator, and i don't get it to work. The only result i get is NaN, and I can't find what's wrong with my code. If the users input is 450 000 or more, the output is supposed to be 32% of their salary else 28%.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="Skatt">
<meta name="author" content="Gandalf">
<title>Taxes</title>
</head>
<body>
<input type="text" id="salary" value="0" />
<button id="button">Calculate tax!</button>
<h2 id="salaryOut">Your salary is NOK:</h2>
<h2 id="taxOut">You should pay taxes with the amount of:</h2>
<script>
var button = document.getElementById("button");
button.onclick = function() {
var salary = document.getElementById("salary");
salary.value = 0;
var salaryOut = document.getElementById("salaryOut");
salaryOut.value = salary;
var salaryOut = document.getElementById("taxOut");
taxOut.value = parseFloat(salaryOut.value);
if(salaryOut.value<450000) {
taxOut.value = salaryOut.value * .28;
}
else {
taxOut.value = salaryOut.value * .32;
}
salaryOut.innerHTML = ("Your salary is NOK: " + salary.value + ",-");
skattUt.innerHTML = "You should pay NOK: " + taxOut.value + ",-";
}
</script>
</body>
</html>

You're performing all of your calculations right away as soon as the page loads, when there are no actual values to calculate. The only thing you're doing in your click handler is displaying the values that were already calculated.
Since there were no values to calculate when the page first loaded, that result is NaN.
Put all of your logic in the click handler:
var knapp = document.getElementById("knapp");
knapp.onclick = function() {
var lonn = document.getElementById("lonn");
var lonnUt = document.getElementById("lonnUt");
var skattUt = document.getElementById("skattUt");
var result = 0;
if(lonn.value<450000) {
result = lonn.value * .28;
}
else {
result = lonn.value * .32;
}
lonnUt.innerHTML = ("Lønnen din er kr: " + lonn.value + ",-");
skattUt.innerHTML = "Skatten din er kr: " + result + ",-";
}
That way you give the user a chance to input numbers before you try to perform calculations on those numbers.
(Note: I keep re-editing this because I'm having a lot of trouble deciphering the actual logic of what you're trying to do. The variable names don't help, since I don't speak that language. It's certainly possible that there are other problems here as well. But the main one is that you need to perform the calculations after the user types the values, not before.)
Edit: I've further modified the code here after finding another significant issue. You were trying to access a .value property on h2 elements, which doesn't exist. You were also trying to store information in those elements as though they were variables.
Instead, just declare a variable to store the result of your calculation. Get the input (lonn), perform the calculation and get a result (result), write the output to the HTML elements (lonnUt and skattUt).

Related

wkhtmltopdf, encoding cyrillic from perl pipe

So, i'm running wkhtmltopdf command script from perl's system method. I need it to pass a custom value (span class) to pdf via command line:
my $time = "Время";
my $command = "./wkhtmltopdf ...blablabla... gen_date \"$time\" ...blablabla...";
but when i run this - i have encoding garbage in output .pdf like that: - Ð​ÑÐμмÑ.
Tried almost everything i know to encode/decode the $time string, but nothing.
my javascript snippet is common for wkhtmltopdf, so....
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<head>
<script>
function subst() {
var vars = {};
var query_strings_from_url = document.location.search.substring(1).split('&');
for (var query_string in query_strings_from_url) {
if (query_strings_from_url.hasOwnProperty(query_string)) {
var temp_var = query_strings_from_url[query_string].split('=', 2);
vars[temp_var[0]] = decodeURI(temp_var[1]);
}
}
var css_selector_classes = ['gen_date', 'page'];
for (var css_class in css_selector_classes) {
if (css_selector_classes.hasOwnProperty(css_class)) {
var element = document.getElementsByClassName(css_selector_classes[css_class]);
for (var j = 0; j < element.length; ++j) {
element[j].textContent = vars[css_selector_classes[css_class]];
}
}
}
}
</script>
</head>
Can you help me to solve it?
After finding a rason why does it happen, i realiased that JS is more likely to operate with its format of byte-array. Now, cyrillic string is encoded to be look like %u0000%u0000... and then in javascript, this string goes through built-in unescape function, and now i have normal cyrillic string in pdf.
Oh, my...

javascript google visualization selection option

I tried to use google spreadsheet to realize drop-down select option!
But I encounter some errors...
In console,it shows that...
**A Parser-blocking, cross-origin script, https://www.google.com/uds/?file=visualization&v=1&packages=corechart%2Cgeomap%2Ctable, is invoked via document.write. This may be blocked by the browser if the device has poor network connectivity.**
**A Parser-blocking, cross-origin script, https://www.google.com/uds/api/visualization/1.0/b5ac9efed10eef460d14e653d0…zh_TW,default+zh_TW,ui+zh_TW,geomap+zh_TW,table+zh_TW,corechart+zh_TW.I.js, is invoked via document.write. This may be blocked by the browser if the device has poor network connectivity.**
I try the tips to fix it, but it can't fix...
Here is the code I have written
<html><head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type=text/javascript>
google.setOnLoadCallback(runQuery);
google.load('visualization', '1',
{
'packages':['corechart', 'table', 'geomap']
}
);function runQuery() {
var tableid = '1zCrjWMRxcedcvdWWAwtc9psQoK8GoGyxy8R53Ga_ztk#gid=0';
var uri = "SELECT geometry FROM " + tableid ;
var queryText = "https://spreadsheets.google.com/tq?key=" + encodeURIComponent(uri);
var query = new google.visualization.Query(queryText);
query.setQuery("select B");
var a = query.setQuery("select B,C,D ");
query.send(function(resp){
if (!resp.isError()) {
var dataTable = resp.getDataTable();
var jsonData = JSON.parse(dataTable.toJSON());
var len = jsonData.rows.length;
console.log(len);
alert(len);
}
});}</script></head><body></body></html>
1) the Parser-blocking message should be just a warning.
regardless, to avoid the message, use loader.js to load the library,
instead of the older library jsapi
you will need to change the load statement, as follows...
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script>
google.charts.load('current', {'packages':['corechart', 'table', 'geomap']});
google.charts.setOnLoadCallback(runQuery);
...
according to the release notes...
The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader from now on.
2) suspect there is another error occuring, check the response messages
see following working snippet, when i run it, the error is Access denied...
google.charts.load('current', {'packages':['corechart', 'table', 'geomap']});
google.charts.setOnLoadCallback(runQuery);
function runQuery() {
var tableid = '1zCrjWMRxcedcvdWWAwtc9psQoK8GoGyxy8R53Ga_ztk#gid=0';
var uri = "SELECT geometry FROM " + tableid ;
var queryText = "https://spreadsheets.google.com/tq?key=" + encodeURIComponent(uri);
var query = new google.visualization.Query(queryText);
query.setQuery("select B");
var a = query.setQuery("select B,C,D ");
query.send(function(resp){
if (!resp.isError()) {
var dataTable = resp.getDataTable();
var jsonData = JSON.parse(dataTable.toJSON());
var len = jsonData.rows.length;
console.log(len);
} else {
console.log('Error: ' + resp.getMessage() + '\nDetails: ' + resp.getDetailedMessage());
}
});}
<script src="https://www.gstatic.com/charts/loader.js"></script>

JSfiddle number guessing game

I have put together a number guessing game in Jsfiddle, im having trouble getting the random number stored into an array. i need to program to pic a random number and store it untill the number is either guessed or the game ends
here is my fiddle link https://jsfiddle.net/e64gt4sv/
any help would be appreciated thanks
HTML code:
<h1>The Guesssing Game</h1> Pick a number between 1 and 1000:
<input id="myAssumption" type="text" />
<input type="submit" id="byBtn" onclick="checkMyAnswer()" value="Click To See If your Correct" />
Js code:
var numberOfSteps = 1;
function checkMyAnswer() {
var actual = Math.floor(Math.random() * 1000) + 1;
var myAnswer = document.getElementById("myAssumption").value; //getting user value
if (myAnswer < actual) { //checking less tha answer
alert("Guessed " + myAnswer + " too low");
numberOfSteps++;
} else if (myAnswer > actual) { //checking grater than answer
alert("Guessed " + myAnswer + " too high");
numberOfSteps++;
} else { //you got answer
alert("Guessed " + myAnswer + " Got it!!");
alert("It tool " + numberOfSteps + " steps");
}
}
I edited the jsfiddle. Check it out https://jsfiddle.net/e64gt4sv/3/.
var numberOfSteps = 1;
var actual = Math.floor(Math.random() * 1000) + 1;
var guesses = [];
function checkMyAnswer() {
...
}
Jeremy is right, each time you call the checkMyAnswer, you regenerated the actual number. Instead, if you set it outside the function, you can still get the value inside the function, but it will only be set each time the actual javascript file loads (meaning each time the page is loaded / reloaded).
Also, I added something to store each guess in an array. The array guesses is a global variable, and then when you call checkMyAnswer(), the value that the user inputted is added to the array by doing
var myAnswer = document.getElementById("myAssumption").value; //getting user value
guesses.push(myAnswer);

Querying MongoDB with values from a text file

I've been handed a list of 500+ email addresses in a text file and been asked to find out how many of them exist as customer emails in our MongoDB database.
What is the quickest way of finding out which of those emails in the text file currently exist in the "Customer.Email" field of my collection?
Can I use text file of emails as parameters for a query, for instance?
Thanks,
Adam
This should do the trick,
I am assuming your txt file is in this format,
test1#test.com
test2#test.com
test3#test.com
test4#test.com
test5#test.com
test6#test.com
test7#test.com
test8#test.com
test9#test.com
test10#test.com
upload the text.txt file to the server for to convert it to an js array
you can do that with something like this,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>File Reader</title>
</head>
<body>
<p>
<script>
function getData() { //this will read file and send information to other function
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
var lines = xmlhttp.responseText;
intoArray(lines);
}
}
xmlhttp.open("GET", "text.txt", true);
xmlhttp.send();
}
getData();
function intoArray(lines) {
var lineArr = lines.split('\n');
//just to check if it works output lineArr[index] as bellow*
lineArr.forEach(function(arrayItem) {
console.log(arrayItem);
});
}
</script>
</body>
</html>
At this point the email address in the txt file will be in an array so you can query the mongodb with the $in Operator like this,
db.Customers.find( {CustomerEmail: { $in [$myArray] } })

Fill in some from HTML form slots using link from another page?

I have a fairly vanilla HTML page with an (inquiry) form. That form has topic field. I'd like to be able to link to that page from another topic-specific page (using an A tag?) on the website, causing that topic field (and maybe some subset of other fields) to be filled in automatically.
Suggestions?
Add a custom param (topic name) to the page where the link points and use it as a subject/topic field.
like:
link
Then, on a target page (with inquiry) use this javascript:
<script type="text/javascript">
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
var params = getUrlVars();
document.getElementById('your_topic_field_id').value = params['topic_title'];
</script>