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.
Related
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)">
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?
I am inputting age in a form in HTML which has a age field. I want to take input in age as a number only so I have defined age field as number type. I am putting a check in the javascript code if(typeof name === "string" && isNaN("age") ==="false").I observed during debugging that typeof age is string.I don't know how is it getting converted to string type automatically.
I have attached my HTML and javascript codes.Plz help...
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery- 1.11.3.min.js"></script>
</head>
<script src="form_js.js"></script>
<body>
<form id="myForm">
First Name:
<input type="text" id="field1">
<br> Last Name:
<input type="text" id="field2">
<br> Age:
<input type="number" id="field3">
<br>
<br> Gender:
<select id="field5">
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</form>
<p>
<input type="button" onclick="insRow('Table1')" value="Insert">
</p>
<table id="Table1" style="width:100%">
<tr>
<td>Name</td>
<td>Age</td>
<td>Gender</td>
</tr>
</table>
</body>
</html>
Javascript:
var count = 0;
function insRow() {
count += 1;
var x, y, z, a, w;
var w = document.getElementById('Table1').insertRow(count);
var name = $("#field1").val() + " " + $("#field2").val();
//var age = $('#field3').val();
//var age = $('#myForm :field3');
//var Email = $("#field4").val();
var gender = $("#field5").val();
//w = document.getElementById('Table1').insertRow(count);
//var first_name = document.getElementById("field1").value;
//var last_name = document.getElementById("field2").value;
var age = document.getElementById("field3").value;
//var gender = document.getElementById("field5").value;
if (typeof name === "string") //&& isNaN("age") ==="false")
{
x = w.insertCell(0);
y = w.insertCell(1);
a = w.insertCell(2);
x.innerHTML = name //" " + last_name;
y.innerHTML = age;
a.innerHTML = gender;
document.getElementById("myForm").reset();
} else alert("Invalid Data");
//var rows += "<tr><td>" + name + "</td><td>" + age + "</td><td>" + Email + "</td><td>" + Gender +"</td></tr>";
//$("#Table1 tbody").append(rows);
}
When you get any value from HTML it is by default string. To convert it to Number use parseInt or parseFloat according to your requirement.
The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).
var age = parseInt(document.getElementById("field3").value, 10);
OR
The parseFloat() function parses a string argument and returns a floating point number.
var age = parseFloat(document.getElementById("field3").value);
When you are checking for NaN, use variable age without quotes. And for strict comparison false should be without quotes.
isNaN("age") ==="false")
Should be
isNaN(age) === false) // Without quotes for age and false
Note that document.getElementById(someId).value will always return you string type, if any. There are several methods to parse like parseInt(), parseFloat() and also +()
var str = document.getElementById('num').value;
var num = +(str);
alert("Type of " + num + " is " + (typeof num));
var price = +(document.getElementById('price').value);
alert("Type of " + price + " is " + (typeof price));
<input type="text" id="num" value="56" />
<input type="text" id="price" value="9.13" />
I'm trying to learn Javascript and I feel like I have a decent grasp on the fundamentals but I am having problems making it do things that i want .. for example.. I am trying to create a simple form in html that calculates the sum of 2 numbers.. here is my html and javascript:
<head>
<script type="text/javascript">
function adder(a,b) {
var a = document.getElementById('firstNum').value;
var b = document.getElementById('secondNum').value;
var numbers = new Array(a,b);
var sum = 0;
for (i=0; i < numbers.length; i++) {
sum += parseInt(numbers[i]);
}
//this part i need help with
document.getElementById('answer').write("First Number: " + a + " plus Second Number: " + b + " is " + sum).value; //this part i need help with
</script>
</head>
<body>
<form id="additionForm">
A + B = C : <input type="text" id="firstNum" placeholder="A">
+ <input type="text" id="secondNum" placeholder="B">
<input type="button" id="addBtn" value="Add" onClick="adder();">
= <input type="text" id="answer" placeholder="C">
</form>
</body>
My problem is that i don't know how to get the javascript to overwrite the value attribute for my form input id=answer .. or if i'm supposed to be using Jquery instead .. thanks in advance.
function adder() {
var a = parseInt( document.getElementById('firstNum').value, 10);
var b = parseInt( document.getElementById('secondNum').value, 10);
var sum = a + b;
//this part i need help with
document.getElementById('answer').value = "First Number: " + a + " plus Second Number: " + b + " is " + sum).value; //this part i need help with
}
If you want to modify an input field in javascript, you can simply set the value attribute:
document.getElementById('answer').value = "First Number: " + a + " plus Second Number: " + b + " is " + sum;