Output not going into .txt file. CS HTML - javascript

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.

Related

Error while input datepicker value into a html table

I try to make an input data into a table html. The other input works fine but I got error while I called the textbox that contains a datepicker value into my table. How to fix it? The error say's like this ("Object Html InputELement").
This is the code:­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
// JavaScript Document
function AddData() {
var x = document.getElementById("material").value;
var y = document.getElementById("kapal").value;
var letters = '/^[a-zA-Z]+$/';
if ((parseInt(x) != (x)) && (y == parseInt(y))) {
alert("Wrong Value Entered");
} else {
var rows = "";
var name = "sadcsad";
var gender = $('input[name="gender"]').val();
var tgl = document.getElementById("datepicker").value;
var nopol = document.getElementById("nopol").value;
var netto = document.getElementById("netto").value;
rows += "<tr><td>" + datepicker + "</td><td>" + nopol + "</td><td>" + netto + "</td></tr>";
$(rows).appendTo("#table_bkk tbody");
}
}
function ResetForm() {
document.getElementById("person").reset();
}
<div id="kanan" class="btn btn-default" style="padding-left:20px" >
<table id="table_bkk" cellspacing='0' class="js-serial" border="2">
<thead>
<tr>
<th><center>No.</center></th>
<th><center>Tanggal</center></th>
<th><center>No.Polisi</center></th>
<th><center>Berat Material</center></th>
</tr>
</thead>
<tbody>
</tbody>
<tr>
<td width="auto" style="border-right:hidden" align="right">Total Bongkaran</td>
<td width="auto" style="border-right:hidden" align="left">:</td>
<td width="auto" style="border-right:hidden">
<td width="auto">
<input type="text" id="sts" type="text" name="sensor1" maxlength="10" size=9 disabled="disabled"> </td>
</tr>
</table>
<script>
function incrementValue()
{
var value = parseInt(document.getElementById('no').value, 10);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById('no').value = value;
}
</script>

What's wrong with my HTML and javascript code?

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.

Javascript not working. No output

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?

javascript issue with inputting a number in a form

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" />

JavaScript - numeric data vs NaN

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);
}
...

Categories