Entry level javascript that I'm trying to finish. Unfortunately my lack of skills won't let me. I know there's working prototypes of this program out but but I want to learn rather than just copy someone elses work.
Thanks
<html>
<head>
<title> 1 </title>
<style type="text/css">
body {
background-color:black;
color:white;
</style>
</head>
<body>
<h1><b> Calculator </h1></b>
<form id="timeForm">
<table>
<tr>
<td>Years:</td>
<td><input type="text" id="years" value="" size="10"></td>
</tr>
<tr>
<td>Months:</td>
<td><input type="text" id="months" value="" size="10"></td>
</tr>
<tr>
<td>Day:</td>
<td><input type="text" id="days" value="" size="10"></td>
</tr>
<tr>
<td> </td>
<td><input type="button" id="button" value="Submit" onclick="handleInput();"></td>
</tr>
</table>
</form>
<p id="output"></p>
<script language="Javascript">
document.getElementById("output").innerHTML = output;
}
function handleInput() {
var form = document.getElementById("timeForm");
try {
var strYears = form.years.value;
var strMonths = form.months.value;
var strDays = form.days.value;
var intYears = parseInt(strYears);
var intMonths = parseInt(strMonths);
var intDays = parseInt(strDays);
if (isNaN(intYears);
throw "Incorrect input. Years is not a number.";
if (intYears > 0 || intYears < 9999)
throw "Incorrect input. Years is out of expected range (0--9999).";
if (isNaN(intYears);
throw "Incorrect input. Months is not a number.";
if (isNaN(intMonths);
throw "Incorrect input. Months is not a number.";
if (intMonths > 0 || intMonths < 9999)
throw "Incorrect input. Months is out of expected range (0--9999).";
if (isNaN(intDays);
throw "Incorrect input. Days is not a number.";
if (intYears > 0 || intDays < 9999)
throw "Incorrect input. Months is out of expected range (0--9999).";
if (m == 1 | | m == 2) {
m = m + 12;
Y = Y - 1;
}
h = (q + Math.floor(13 * (m + 1) / 5) + Y + Math.floor(Y / 4)
- Math.floor(Y / 100) + Math.floor(Y / 400)) % 7;
{
var output = "Weekday" = " + years + ":" + months + ":" + days + ".";
catch (error) {
document.getElementById("output").innerHTML = "ERROR: " + error;
}
}
</script>
</body>
</html>
There is a whole bunch of syntax errors preventing the browser to execute your JavaScript.
If you want to see those, you can use your browser's developer tools to figure out where it choked.
The language attribute has been deprecated for a long time, as someone said in here link (and its true) so you don't have to put it there anymore, you should put the document.getElementById("output").innerHTML = output; under everything in your javascript script.
And you have a } there
document.getElementById("output").innerHTML = output;
}
Whats up with that?
Related
I'm stuck on trying to get the email outputted instead of numbers related to the amount of words inputed
var output2 = "Email: " + at; is counting the amount of letters that was inputed.
I'm trying to figure out how its counting the amount of letters and why is it not outputting the email instead
Demo in Stack Snippets
function myFunction() {
var uname = document.getElementById("uname").value;
var age = document.getElementById("age").value;
var at = document.getElementById("email").value.indexOf("#");
submitOk = "true";
if (uname.length > 16) {
alert("Characters have exceeded specified amount");
submitOk = "false";
}
if (age < 13 || age > 19) {
alert("Numbers must be between 13 and 19");
submitOk = "false";
}
if (at == -1) {
alert("not a valid E-mail");
}
if (submitOk == "false") {}
if (submitOk == "true") {}
var output = "Name: " + uname;
var output1 = "Age: " + age;
var output2 = "Email: " + at;
document.getElementById("output").innerHTML = output;
document.getElementById("output1").innerHTML = output1;
document.getElementById("output2").innerHTML = output2;
}
<form onsubmit="return myFunction()">
Name : <br><input type="text" id="uname" size="30" placeholder="Maximum of 16 Characters"><br> Age : <br><input type="number" id="age" size="30" placeholder="From 13 to 19 only"><br> E-mail : <br><input type="text" id="email" size="30" placeholder="Examplename#mail.com"><br>
<br>
<input type="submit" onclick="myFunction();return false" value="Submit">
</form>
<table class="center">
<tr>
<td>
<div id="output"></div>
</td>
</tr>
<tr>
<td>
<div id="output1"></div>
</td>
</tr>
<tr>
<td>
<div id="output2"></div>
</td>
</tr>
</table>
It looks like at is being used to verify that the email has an # symbol, not neccessarily return the pure value as seen here where it's calculated:
var at = document.getElementById("email").value.indexOf("#");
indexOf("#") will return the position of the first at symbol if found, or -1 if not found.
If you just want the email address, you can break into two statements:
var email = document.getElementById("email").value;
var at = email.indexOf("#");
I created an array below to store the information required.
My expected output should be smth like:
John,2
May,3
The values beside the name is supposed to increment and replace the old value itself whenever the user presses on the specific button id.
Not sure why the information is not being written into the data.txt file.
Please advise. Thank you.
#{
var result = "";
if (IsPost)
{
char[] delimiterChar = { ',' };
var dataFile = Server.MapPath(#"~/App_Data/data.txt");
string[] votesArr = File.ReadAllLines(dataFile);
if (votesArr == null)
{
// Empty file.
result = "The file is empty.";
}
string toWrite = "";
for (int i = 0; i < votesArr.Length - 2; i += 2)
{
if (votesArr[i].Equals("Harry")) // Equals here is hardcoded, replace with parameter
{
votesArr[i + 1] = "" + (Int32.Parse(votesArr[i + 1]) + 1);
}
else if (votesArr[i].Equals("John")) // Equals here is hardcoded, replace with parameter
{
votesArr[i + 1] = "" + (Int32.Parse(votesArr[i + 1]) + 1);
}
else if (votesArr[i].Equals("May")) // Equals here is hardcoded, replace with parameter
{
votesArr[i + 1] = "" + (Int32.Parse(votesArr[i + 1]) + 1);
}
else if (votesArr[i].Equals("Jane")) // Equals here is hardcoded, replace with parameter
{
votesArr[i + 1] = "" + (Int32.Parse(votesArr[i + 1]) + 1);
}
toWrite += votesArr[i] + votesArr[i + 1];
}
File.WriteAllText(dataFile, toWrite);
result = "Information is saved.";
}
}
<!DOCTYPE html>
<html>
<head>
<title>Elections</title>
</head>
<body>
<form id="form1" method="post">
<div>
<table>
<tr>
<td>Harry</td>
<td><input id="Harry" name="submit" type="submit" value="Vote Harry" /></td>
</tr>
<tr>
<td>John</td>
<td><input id="John" name="submit" type="submit" value="Vote John" /></td>
</tr>
<tr>
<td>Bryan</td>
<td><input id="Bryan" name="submit" type="submit" value="Vote Bryan" /></td>
</tr>
<tr>
<td>Jack</td>
<td><input id="Jack" name="submit" type="submit" value="Vote Jack" /></td>
</tr>
</table>
</div>
<div>
#if (result != "")
{
<p>Result: #result</p>
}
</div>
</form>
</body>
</html>
You are not parsing the HTMl file. You are just reading it straight into the array.
Therefore each line in the array will contain the HTML syntax also, but you are not checking for that, you are just doing an .Equals("Harry") and it will never be equal to "Harry" because it's surrounded by the HTML markup.
You need to use something like Angle Sharp to parse up HTML and extract text.
I am going through the SAMS Learn JavaScript in 24 hours book. The end of lesson three has an extra exercise to combine a Celsius to Fahrenheit from Lesson 2, with functions and buttons from Lesson 3. I was able to successfully complete the Try It exercises in Lessons 2 and 3...
LESSON 2
<!DOCTYPE html>
<html>
<head>
<title>Fahrenheit From Celsius</title>
</head>
<body>
<script>
var cTemp = 100; // temperature in Celsius
var hTemp = ((cTemp * 9) /5 ) + 32;
document.write("Temperature in Celsius: " + cTemp + " degrees<br/>");
document.write("Temperature in Fahrenheit: " + hTemp + " degrees");
</script>
LESSON 3
<!DOCTYPE html>
<html>
<head>
<title>Calling Functions</title>
<script>
function buttonReport(buttonId, buttonName, buttonValue) {
var userMessage1 = "Button id: " + buttonId + "\n";
var userMessage2 = "Button name: " + buttonName + "\n";
var userMessage3 = "Button value: " + buttonValue;
alert(userMessage1 + userMessage2 + userMessage3);
}
</script>
But I am stuck combining the two.
EXERCISE TO COMBINE THE TWO:
Write a function to take a temperature value in Celsius as an argument and return the equivalent temperature in Fahrenheit, basing it on the code from Lesson 2.
Test your function in an HTML page having three buttons that, when clicked, pass values of 10, 20, and 30 degrees Celsius, respectively, to the function.
HERE'S WHAT I HAVE...(minus the headers, titles and HTML tags)
function temp(10, 20, 30) {
var hTemp1 = ((temp * 9) /5 ) + 32;
var hTemp2 = ((temp * 9) /5 ) + 32;
var hTemp3 = ((temp * 9) /5 ) + 32;
alert(hTemp1, hTemp2, hTemp3);
}
</script>
</head>
<body>
<input type="button" value="10 X Celsius" onclick = hTemp1>
<input type="button" value="20 X Celsius" onclick = hTemp2>
<input type="button" value="30 X Celsius" onclick = hTemp3>
Can you please help me?
There's definitely better ways to do this. But here's a solution for the purpose of this lesson. I tried not to change too much of your code. Check out the snippet below.
function toF(cTmp) {
return cTmp * 9 / 5 + 32
}
function alertF(tmp) {
alert(toF(tmp))
}
<input type="button" value="10" onclick="alertF(10)">
<input type="button" value="20" onclick="alertF(20)">
<input type="button" value="30" onclick="alertF(30)">
I want to implement a simple measurement convergence program but the convert button doesn't really work and it's not even changing the value of the answer box. What should I do now?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Measurement Conversion</title>
</head>
<body>
<h1 align="center">
Measurement Conversion
</h1>
<div align="center"><center><table border="0">
<tr>
<input type="text" name="what" size="15">
</tr>
<tr>
<td align="center">From:<br>
<select name="unit" size="9" onChange="convert()">
<option name="meter">meter</option>
<option name="mile">mile</option>
<option name="yard">yard</option>
</select></td>
</tr>
<tr>
<input type="button" onclick="convert()">Convert it now!</button></td>
</tr>
<tr>
<input type="text" name="answer" title="answer" size="70" value="None"></td>
</tr>
</table>
</center></div>
<script>
function convert() {
// var FromVal, ToVal, FromName, ToName, v1;
v1 = document.getElementByName("what").value;
document.getElementByName("answer").value = v1;
var unit = document.getElementByName("unit").name;
if (unit == "yard") {
var meter = "meter= " + 0.9144*document.getElementByName("what").value;
var mile = "mile = " + 0.000568181818*document.getElementByName("what").value;
document.getElementById("answer").value = meter + mile;
}
if (unit == "meter") {
var yard = "yard = " + 1.0936133*document.getElementByName("what").value;
var mile = "mile = " + 0.000621371192*document.getElementByName("what").value;
// var meter = "m = " + 0.9144*document.getElementByName("what").value
document.getElementById("answer").value = yard + mile;
}
if (unit == "mile") {
var meter = "meter = " + 1609.344*document.getElementByName("what").value
var yard = "yard = " + 1760*document.getElementByName("what").value
document.getElementById("answer").value = meter + yard;
}
}
</script>
</body>
</html>
It seems there is something wrong with my convert() function.
How about using the most basic troubleshooting methods first and then coming here and asking specific questions to help get you through the problem.
Add an alert("button Clicked");
to the first line of your function and see if you get the alert. If you do, move the alert to after your variable statements and change it to
alert("what = " + what + ", "answer = " + answer + ", unit = " + unit);
and make sure you are getting what you expect for your variable assignments. Continue like this and when you get to a specific problem that your can't seem to remedy yourself, come back.
there's no getElementByName.
add attribute id on your input then use getElementById instead.
I'm sure I'm contravening some deep dark law of javascript, but I'm not really a JS developer and this is driving me mad. This function is called on an orderform to read the quantity and price of items, row by row, and then provide the subtotal, delivery and total.
The problem is with line 10 - it keeps "forgetting" that the variable data throughout is numeric (floating point) and so returns lots of NaN. How can I force the variables throughout this function to behave as numbers rather than strings?
EDIT
Here's the revised code based on feedback so far (thank you!). It's still not working ;)
<script type="text/javascript">
function subTotal(rows) {
var i, subTotal, lineTotal, orderShip, orderTotal;
for (i = 1; i <= rows; ++i) {
//Grab values from form
var quantity = parseFloat($('#quantity' + i).val());
var uPrice = parseFloat($('#uPrice' + i).val());
//Error checking
alert('quantity = ' + quantity +' and uPrice = ' + uPrice);
if (isNaN(quantity)) alert('quantity = NaN');
if (isNaN(uPrice)) alert('uPrice = NaN');
if ((quantity == '') || (uPrice == '')) {
} else {
lineTotal = quantity * uPrice;
alert('lineTotal = ' + lineTotal);
subTotal += lineTotal;
alert('subTotal = ' + subTotal);
}
//If we've maxed out the number of rows, then subTotal should be calculated - push back to form.
if (i == rows) {
$('#orderSubTotal').val(subTotal );
orderShip = subTotal * 0.25;
$('#orderShip').val(orderShip.toFixed(2));
orderTotal = subTotal + orderShip;
$('#orderTotal').val(orderTotal.toFixed(2));
}
}
}
</script>
<form>
<table>
<tr>
<td><input type="text" id="item1" name="item1" value="Some description" readonly="readonly" /></td>
<td><input type="text" id="quantity1" name="quantity1" value="25" onchange="javascript:subTotal('2')" /></td>
<td><input type="text" id="uPrice1" name="uPrice1" value="1.50" readonly="readonly" /></td>
</tr>
<tr>
<td><input type="text" id="item2" name="item2" value="Some description" readonly="readonly" /></td>
<td><input type="text" id="quantity2" name="quantity2" value="25" onchange="javascript:subTotal('2')" /></td>
<td><input type="text" id="uPrice2" name="uPrice2" value="2.75" readonly="readonly" /></td>
</tr>
<tr>
<td colspan="3">
SubTotal
<input type="text" id="orderSubTotal" name="orderSubTotal" readonly="readonly" style="text-align: right" value="0.00" />
<br />Shipping
<input type="text" id="orderShip" name="orderShip" readonly="readonly" style="text-align: right" value="0.00" />
<br />Total
<input type="text" id="orderTotal" name="orderTotal" readonly="readonly" style="text-align: right" value="0.00" />
</td>
</tr>
</table>
</form>
I think the real problem is in your loop: You're looping from 0 to rows inclusive. So if you pass in 10 for rows, you'll be looping 11 times, starting with 0 and continuing through (including) 10. I suspect that's your real problem. If you don't have a quantity0 element, or (assuming rows is 10) you don't have a quantity10 element, then $("#quantity" + i).val() will return undefined, which converts to NaN when you convert it (implicitly or explicitly). (And the same for uPrice0 / uPrice10.) And of course, once you have NaN, any mathematical operation using it results in NaN.
In terms of your question about how to ensure they don't change, basically, convert them to numbers early. You're currently using quantity and uPrice without converting them, which means initially they're strings. Now, JavaScript is pretty smart about converting them for you, but sometimes you want to be explicit.
Separately: Where does x come from?
You haven't shown any data to work with, but just speculatively:
function subTotal(rows) {
var i, subTotal, lineTotal, quantity, uPrice, orderShip, orderTotal;
subTotal = 0;
for (i = 0; i < rows; ++i) {
// OR
//for (i = 1; i <= rows; ++i) {
quantity = $('#quantity' + i).val();
uPrice = $('#uPrice' + i).val();
if ((quantity == '') || (uPrice == '')) {
} else {
quantity = parseFloat(quantity);
uPrice = parseFloat(uPrice);
// Might consider checking isNaN(quantity) and isNan(uPrice) here
lineTotal = quantity * uPrice;
subTotal += lineTotal;
alert('subtotal = ' + subTotal);
}
if (i == x) { // Where does `x` come from?
$('#orderSubTotal').val(subTotal );
orderShip = subTotal * 0.25;
$('#orderShip').val(orderShip.toFixed(2));
orderTotal = subTotal + orderShip;
$('#orderTotal').val(orderTotal.toFixed(2));
}
}
}
The problem is that you're performing a mathematical calculation on the fields before using parseFloat:
var lineTotal = quantity * uPrice; // <-- result is most likely NaN here
subTotal = parseFloat(subTotal ) + parseFloat(lineTotal);
Perform your parsing at the point you get the values to make life a little easier:
var quantity = parseFloat($('#quantity' + i).val());
var uPrice = parseFloat($('#uPrice' + i).val());
Then change the subTotal = line to this:
subTotal += lineTotal;
Another possible issue is if the result of $('#uPrice' + i).val() doesn't start with a parseable float — if it starts with a currency symbol, e.g. £ or $, for instance — parseFloat will always return NaN for that field. You can work around it using $('#uPrice' + i).val().slice(1).
Do some error checking:
function subTotal(rows) {
var subTotal = 0;
while (var i=0; i < rows; i++) {
// convert as soon as you get the values
var quantity = parseFloat($('#quantity' + i).val());
var uPrice = parseFloat($('#uPrice' + i).val());
if (isNaN(quantity) || isNaN(uPrice)) { // error checking
alert("Invalid values on row " + i);
continue;
}
var lineTotal = quantity * uPrice;
subTotal += lineTotal;
alert('subtotal = ' + subTotal);
if (i == x) {
$('#orderSubTotal').val(subTotal );
var orderShip = subTotal * 0.25;
$('#orderShip').val(orderShip.toFixed(2));
var orderTotal = subTotal + orderShip;
$('#orderTotal').val(orderTotal.toFixed(2));
}
}
}
You're probably running into an index problem at some point, getting a NaN from one of the (non-existing fields), adding it to subTotal which makes it a NaN instantly.
You better convert the value before doing any mathematical operation. So the code should be:
var numQuanitity = parseFloat(quantity);
var numPrice = parseFloat(uPrice);
if (isNaN(numQuanitity) || isNaN(numPrice)) {
//you can alert or ignore
}
else {
var lineTotal = numQuanitity * numPrice;
subTotal += lineTotal;
alert('subtotal = ' + subTotal);
}
...