i am new for javascript, im trying to calculate function but not working
<script>
function calculator() {
var first_name = document.getElementById('value1').value;
//alert("first_name");
var last_name = document.gerElementById('value2').value;
var add = first_name + last_name;
document.write("add");
}
</script>
<div id="cal">
<table>
<tr>
<td><input type="text" name="value1" id="value1" value=""></td>
<td><input type="text" name="value2" id="value2"></td>
<td><button onclick="calculator()" type="button">+</button></td>
</tr>
</table>
</div>
Tested code working fine.
<html>
<head>
<title></title>
<script type="text/javascript">
function calculator() {
var first_name = document.getElementById('value1').value;
//alert("first_name");
alert(first_name);
// var last_name = document.gerElementById('value2').value;
var last_name = document.getElementById('value2').value;
//var add = first_name+last_name;
var add = parseInt(first_name) + parseInt(last_name);
//document.write("add");
document.write(add);
}
</script>
</head>
<body>
<input id="value1" />
<input id="value2" />
<input type="button" onclick="calculator()" value="Add" />
</body>
</html>
Commented line show your code.
function calculator()
{
var first_name = parseInt(document.getElementById('value1').value);
//alert("first_name");
var last_name = parseInt(document.getElementById('value2').value);
var add = first_name + last_name;
document.write(add);
}
</script>
<table>
<tr>
<td><input type="text" name="value1" id="value1" value=""></td>
<td><input type="text" name="value2" id="value2"></td>
<td><button onclick="calculator()" type="button">+</button></td>
</tr>
</table>
</div>
You need to parseInt to perform the addition
else it will take the values as string and concatenate them
You have typo here gerElementById it should be getElementById
var last_name = document.gerElementById('value2').value;
change it to
var last_name = document.getElementById('value2').value;
and of course you are writing a string not the variable add in the document.write();
change it with
document.write(add);
check this link as well http://jsfiddle.net/E9RVn/
You are writing a string with the "add"
Remove the " " quotations
document.write(add);
They actually strings are not numbers. So, easiest way to produce a number from a string is to prepend it with +. Like :
var add = +first_name + +last_name;
<script>
function calculator() {
var first_name = document.getElementById('value1').value;
//alert("first_name");
var last_name = document.gerElementById('value2').value;
var add = parseInt(first_name) + parseInt(last_name);
document.write(add);
}
</script>
<div id="cal">
<table>
<tr>
<td><input type="text" name="value1" id="value1" value=""></td>
<td><input type="text" name="value2" id="value2"></td>
<td><button onclick="calculator()" type="button">+</button></td>
</tr>
</table>
</div>
Silly mistakes in code.
getElementById was incorrect
Values were not parsed
Below is corrected:
<script>
function calculator() {
var first_name = parseInt(document.getElementById('value1').value, 10);
//alert("first_name");
var last_name = parseInt(document.getElementById('value2').value, 10);
var add = first_name + last_name;
document.write(add);
}
</script>
<div id="cal">
<table>
<tr>
<td><input type="text" name="value1" id="value1"></td>
<td><input type="text" name="value2" id="value2"></td>
<td><button onclick="calculator()" type="button">+</button></td>
</tr>
</table>
</div>
Another way to do calculation without parsing:
<script>
function calculator() {
var first_name = document.getElementById('value1').value;
var last_name = document.getElementById('value2').value;
var cal = first_name+"+"+last_name;
var add = eval(cal);
document.write(add);
}
</script>
Ref: http://www.w3schools.com/jsref/jsref_eval.asp
Related
I've been using JavaScript to create new row on the table so that each input data will save in database. please refer example below.
Script for adding row on the table
<script type="text/javascript">
$(document).ready(function(){
var html='<tr><td><input type="text" size="2" class="form-control" name="qt[]" id="qt"
oninput="calculate();" required></td>
<input type="text" size="5" class="form-control" name="uc[]" id="cf" oninput="calculate();"
placeholder="₱0.00" required></td>
<td><center><input type="text" size="5" class="form-control" name="ta[]" id="result"
required></center></td><input type="button" class="form-control" name="remove" id="remove"
value="-"></td></tr>';
var x = 1;
$("#addd").click(function(){
$("#tb_field").append(html);
});
$("#tb_field").on('click','#remove',function(){
$(this).closest('tr').remove();
x--;
});
});
</script>
Script for multiplying two input types in the first row of the table
<script>
function calculate() {
var myBox1 = document.getElementById("qt").value;
var myBox2 = document.getElementById("cf").value;
var result = document.getElementById("result");
var myResult = myBox1 * myBox2;
var format2 = myResult.toLocaleString("USD");
document.getElementById("result").value = format2;
}
</script>
I made a working JSFiddle example. The code is:
<table id="myTable">
</table>
<input type="button" name="addRow" id="addRow" value="+">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js?Version=43"></script>
<script>
function newRowHtml(rowNumber)
{
return '<tr id="row'+rowNumber+'"><td><input type="text" size="2" name="qt[]" class="qt" oninput="calculate('+rowNumber+');" value="0" required></td><td><input type="text" size="5" name="uc[]" class="cf" oninput="calculate('+rowNumber+');" value="0" required></td><td><center><input type="text" size="5" name="ta[]" class="ta" required></center></td><td><input type="button" name="remove" id="removeRow" value="-"></td></tr>';
}
var rowNumber = 1;
$("#addRow").click(function() {
$("#myTable").append(newRowHtml(rowNumber));
calculate(rowNumber);
rowNumber++;
});
$("#myTable").on('click', '#removeRow', function() {
$(this).closest('tr').remove();
});
function calculate(rowNumber)
{
let row = $("#row"+rowNumber);
let qt = parseInt(row.find(".qt").val());
let cf = parseInt(row.find(".cf").val());
row.find(".ta").val(qt * cf);
}
</script>
I have numbered the rows, which is easier than number cells, and make fully use of JQuery. I hope this makes some sense, and that you can adapt it to your needs.
You can, of course, use parseFloat() instead of parseInt(), but having values like ₱0.00 in your input could complicate things.
Converting oclick() with addEventListener(), i have tried multiple times, But no Success. Can anyone help please. i have read in the book, that onlick() is not w3 standard, Any help will highly be aprreciated
Before with onclick() working Perfectly:
html code
<!DOCTYPE html>
<html>
<head>
<title>Splitting number</title>
<script type="text/javascript" src="script.js">
</script>
</head>
<body>
<form id="myForm" action="" name="myForm">
<table border="1">
<tr>
<td>Enter a phone number<br> [in the form (555) 555-5555]</td>
<td><input name="input" type="text" size="40"></td>
</tr>
<tr>
<td><input type="button" value="Split" onclick="parseNumber()"></td>
</tr>
<tr>
<td>Area code:</td>
<td><input name="areaCode" type="text" size="5"></td>
</tr>
<tr>
<td>Number:</td>
<td><input name="number" type="text" size="8"></td>
</tr>
</table>
</form>
</body>
</html>
javascript code:
function parseNumber() {
var myForm = document.getElementById( "myForm" );
myForm.areaCode.value = "";
myForm.number.value = "";
var completeNumber = myForm.input.value.replace(/\s/g, '');
var areaCode = completeNumber.substr(1,3);
var tokens2 = completeNumber.substr(5).split( "-" );
myForm.areaCode.value = areaCode;
myForm.number.value = tokens2[0] + "-" + tokens2[1];
}
after, Not working:
html code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Splitting number</title>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
Enter a phone number: in the form (555) 555-5555]
<input name="input" type="text" size="40" id="number" ><br>
<input type="button" value="Split" id="myBtn"><br><br>
Area code: <input name="areaCode" type="text" size="5" id="areaCode"><br>
Number: <input name="number" type="text" size="8" id="anotherNumber">
</body>
</html>
javascript code
var completeNumber = document.getElementById("number");
x = document.getElementById( "myBtn" );
function parseNumber() {
x.addEventListener("click", parseNumber);
completeNumber.replace(/\s/g, '');
var areaCode = completeNumber.substr(1,3);
var tokens2 = completeNumber.substr(5).split( "-" );
document.getElementById("areaCode").innerHTML = areaCode.toString();
document.getElementById("anotherNumber").innerHTML = tokens2[0].toString() + "-" + tokens2[1].toString();
}
You need to add the event listener outside the function.
The listener is listening (clues in the name) for a mouse 'click' event on that element. When the event happens i.e you click on the element, it calls the function that it is assigned, in your case: parseNumber.
So since you are adding the event listener inside the function, it never gets added (as the function never gets called).
It should all work if you move the lines:
var x = document.getElementById( "myBtn" );
x.addEventListener("click", parseNumber);
outside the function. :)
I thnik no one actually read the question, if you already had a working example then changing onclick to eventListener is no problem:
var parseNum = document.getElementById('parse-number');
function parseNumber() {
var myForm = document.getElementById( "myForm" );
myForm.areaCode.value = "";
myForm.number.value = "";
var completeNumber = myForm.input.value.replace(/\s/g, '');
var areaCode = completeNumber.substr(1,3);
var tokens2 = completeNumber.substr(5).split( "-" );
myForm.areaCode.value = areaCode;
myForm.number.value = tokens2[0] + "-" + tokens2[1];
}
parseNum.addEventListener("click", parseNumber);
<form id="myForm" action="" name="myForm">
<table border="1">
<tr>
<td>Enter a phone number<br> [in the form (555) 555-5555]</td>
<td><input name="input" type="text" size="40"></td>
</tr>
<tr>
<td><input type="button" value="Split" id="parse-number"></td>
</tr>
<tr>
<td>Area code:</td>
<td><input name="areaCode" type="text" size="5"></td>
</tr>
<tr>
<td>Number:</td>
<td><input name="number" type="text" size="8"></td>
</tr>
</table>
</form>
Change your code to this where eventListener is added outside the bounded function. Otherwise it will repeatedly bind an eventListener to the button.
Also place your script.js on the bottom of the HTML page. Because when the script executed the DOM element is not found since the DOM is not rendered at the script execution time.
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Splitting number</title>
</head>
<body>
Enter a phone number: in the form (555) 555-5555]
<input name="input" type="text" size="40" id="number" ><br>
<input type="button" value="Split" id="myBtn"><br><br>
Area code: <input name="areaCode" type="text" size="5" id="areaCode"><br>
Number: <input name="number" type="text" size="8" id="anotherNumber">
<script type="text/javascript" src="script.js"></script>
</body>
</html>
JavaScript
var completeNumber = document.getElementById("number");
var x = document.getElementById( "myBtn" );
function parseNumber() {
completeNumber.replace(/\s/g, '');
var areaCode = completeNumber.substr(1,3);
var tokens2 = completeNumber.substr(5).split( "-" );
document.getElementById("areaCode").innerHTML = areaCode.toString();
document.getElementById("anotherNumber").innerHTML = tokens2[0].toString() + "-" + tokens2[1].toString();
}
x.addEventListener("click", parseNumber);
Ok, here I have a Jquery Accordian with 2 tabs.
1 is for SELL and the other one is BUY.Each one of them has it's own group of input boxes and javascript attached to them.
Here's for the BUY tab
Input Boxes:-
<tr>
<td>BUY <input type="text" name="buybtc" id="buybtc" class="validate[required] text-input" placeholder="amount" size="10"> BTC </td>
<td>At Rate<input type="text" name="rate" id="rate" class="validate[required] text-input" placeholder="rate" size="10">BTC/LTC</td>
</tr>
<tr>
<td>LTC You will give<input type="text" name="giveltc" readonly id="giveltc" size="10"></td>
</tr>
Javascript:-
<script type="text/javascript">
window.onload = function(){
var buybtc = document.getElementById('buybtc'), //get the amount BTC to be sold
giveltc = document.getElementById('giveltc'),
rate = document.getElementById('rate');
var constantNumber = 0.022632;
rate.onkeyup = function () {
var result = parseFloat(buybtc.value) * parseFloat(rate.value);
giveltc.value = !isNaN(result) ? result : '';
};
}
//sellbtc = buybtc
//getltc = giveltc
</script>
SELL Tab :-
Input Boxes
<tr>
<td>Sell <input type="text" name="sellbtc" id="sellbtc" class="validate[required] text-input" placeholder="amount"> BTC </td>
<td>At Rate<input type="text" name="rates" id="rates" class="validate[required] text-input" placeholder="rate">LTC/BTC</td>
</tr>
<tr>
<td>LTC You will get<input type="text" name="getltc" readonly id="getltc"></td>
</tr>
Javascript :-
<script type="text/javascript">
window.onload = function(){
var sellbtc = document.getElementById('sellbtc'), //get the amount BTC to be sold
getltc = document.getElementById('getltc'),
rate = document.getElementById('rate');
var constantNumber = 0.022632;
rate.onkeyup = function () {
var result = parseFloat(sellbtc.value) * parseFloat(rate.value);
getltc.value = !isNaN(result) ? result : '';
};
}
</script>
The work of both these scripts is to calculate the total amount based on the principle amount and rate.The problem is, that when I put only 1 javascript in the page (for the buy tab)..everything works fine..i.e, the amount is calculated in the third box.But, the moment I place the javascript for the BUY tab..both the javascripts stop working, that means the final amount is not calculated in any of these tabs.
How should I tackled this problem?
Thanks.
Updated:-
<script type="text/javascript">
window.onload = function(){
var sellbtc = document.getElementById('sellbtc'), //get the amount BTC to be sold
getltc = document.getElementById('getltc'),
rate = document.getElementById('rate');
var constantNumber = 0.022632;
rate.onkeyup = function () {
var result = parseFloat(sellbtc.value) * parseFloat(rate.value);
getltc.value = !isNaN(result) ? result : '';
};
}
</script>
<script type="text/javascript">
window.onload = function(){
var buybtc = document.getElementById('buybtc'), //get the amount BTC to be sold
giveltc = document.getElementById('giveltc'),
rateSell = document.getElementById('rateSell');
var constantNumber = 0.022632;
rate.onkeyup = function () {
var resultSell = parseFloat(buybtc.value) * parseFloat(rateSell.value);
giveltc.value = !isNaN(resultSell) ? resultSell : '';
};
}
//sellbtc = buybtc
//getltc = giveltc
</script>
<div id="accordion">
<h3>Buy</h3>
<div>
<p>
<form action="tradehandler.php?action=buy" method="post" id="formID">
<table>
<tr>
<td>BUY <input type="text" name="buybtc" id="buybtc" class="validate[required] text-input" placeholder="amount" size="10"> BTC </td>
<td>At Rate<input type="text" name="rateSell" id="rateSell" class="validate[required] text-input" placeholder="rate" size="10">BTC/LTC</td>
</tr>
<tr>
<td>LTC You will give<input type="text" name="giveltc" readonly id="giveltc" size="10"></td>
</tr>
<tr>
<td><input type="submit" name="submit"></td>
</tr>
</table>
</form>
</p>
</div>
<h3>Sell</h3>
<div>
<p>
<form action="tradehandler.php?action=sell" method="post" id="formID">
<table>
<tr>
<td>Sell <input type="text" name="sellbtc" id="sellbtc" class="validate[required] text-input" placeholder="amount"> BTC </td>
<td>At Rate<input type="text" name="rate" id="rate" class="validate[required] text-input" placeholder="rate">LTC/BTC</td>
</tr>
<tr>
<td>LTC You will get<input type="text" name="getltc" readonly id="getltc"></td>
</tr>
<tr>
<td><input type="submit" name="submit"></td>
</tr>
</table>
</form>
</p>
</div>
</div>
this work only for sell div
<script type="text/javascript">
window.onload = function(){
setAccordion('sellbtc','getltc','rates');
};
}
function setAccordion(btc,ltc,rate)
{
var sellbtc = document.getElementById(btc), //get the amount BTC to be sold
getltc = document.getElementById(ltc),
rateVar = document.getElementById(rate);
var constantNumber = 0.022632;
rateVar.onkeyup = function () {
var result = parseFloat(sellbtc.value) * parseFloat(rate.value);
getltc.value = !isNaN(result) ? result : '';
}
</script>
if they are on the same page, you have to change the ID of rates and ltc in the SELL div
and change the script like this:
<script type="text/javascript">
window.onload = function(){
setAccordion('buybtc','getltc','rates');
setAccordion('sellbtc','SELLgetltc','SELLrates');
};
}
function setAccordion(btc,ltc,rate)
{
var sellbtc = document.getElementById(btc), //get the amount BTC to be sold
getltc = document.getElementById(ltc),
rateVar = document.getElementById(rate);
var constantNumber = 0.022632;
rateVar.onkeyup = function () {
var result = parseFloat(sellbtc.value) * parseFloat(rate.value);
getltc.value = !isNaN(result) ? result : '';
}
</script>
I am creating a form which adds a table row on a button click so far its working fine but I want to have a delete button beside every row generated by the button click, but not on the first row. I've searched many blogs but came up with nothing can anyone guide me in doing it? I am just a beginner.
Here is my script:
<?php
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<script language="javascript" type="text/javascript">
var i=1;
function addRow()
{
var tbl = document.getElementById('table1');
var lastRow = tbl.rows.length;
var iteration = lastRow - 1;
var row = tbl.insertRow(lastRow);
var firstCell = row.insertCell(0);
var el = document.createElement('input');
el.type = 'text';
el.name = 'name' + i;
el.id = 'name' + i;
el.size = 20;
el.maxlength = 20;
firstCell.appendChild(el);
var secondCell = row.insertCell(1);
var el2 = document.createElement('input');
el2.type = 'text';
el2.name = 'address' + i;
el2.id = 'address' + i;
el2.size = 20;
el2.maxlength = 20;
secondCell.appendChild(el2);
var thirdCell = row.insertCell(2);
var el3 = document.createElement('input');
el3.type = 'text';
el3.name = 'contactNum' + i;
el3.id = 'contactNum' + i;
el3.size = 20;
el3.maxlength = 20;
thirdCell.appendChild(el3);
frm.h.value=i;
i++;
}
</script>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title></head>
<body>
<form action="submit.php" method="post" name="frm" id="frm">
<table width="40%" border="2" cellpadding="0" cellspacing="0" id="table1">
<tr>
<td><strong>Name</strong></td>
<td><strong>Address</strong> </td>
<td><strong>Contact Num</strong> </td>
</tr>
<tr>
<td><input name="name" type="text" id="name" size="20" maxlength="20" /></td>
<td><input name="address" type="text" id="address" size="20" maxlength="20" /></td>
<td><input name="contactNum" type="text" id="contactNum" size="20" maxlength="12" /></td>
</tr>
</table>
<input type="button" value="Add" onclick="addRow();" />
<input name="Submit" type="submit" value="Submit" />
<label>
<input name="h" type="hidden" id="h" value="0" />
</label>
</form>
</body>
</html>
I think you are looking for add row jquery plugin.
You can use the deleteRow() method with the rowIndex property. Try using an onClick(this) call for the button in the row.
Better try to search for data tables.. They can be used directly. You need not code in more also.. You also have many other features embedded in it.
I had post this problem before, dealing with the shopping cart application. The application so far does everything that i would like it to do. I'm able to store and retrieve the cookies. But right now, my problem is extracting the individual values from the cookies and placing them into a table i have created. This is the format of the cookie when retrieved.
ItemName = quantity$price. what i am trying to do is retrieve the quantity and price values from the cookie, and display that data into my table. the cookie is being created in my store page, and then retrieved and displayed in my cart page. here is the code for my store page
store.html
<html>
<head>
<title> Store </title>
<h1> My store </h1>
<script type="text/javascript">
function retr(circle)
{
var cke = document.cookie.split(';');
var nameCk= name + "=";
for(var i=0; i < cke.length; i++)
{
var c = cke [i];
while (c.charAt(0)==' ') c = c.substring(1, c.length);
if (c.indexOf(nameCk) == 0)
return c.substring(nameCk.length, c.length);
}
return null;
}
function createCookie()
{
var exdate = new Date();
exdate.setDate(exdate.getDate() +10);
if (document.getElementById("circle").checked)
{
document.cookie = "Circle=" + document.getElementById("quantity1").value + document.getElementById("price1").value + ";expires="+exdate.toGMTString();
}
}
function retrieve()
{
if (document.getElementById("circle").checked)
{
document.getElementById("ret").value = document.cookie;
}
}
function Calc()
{
var fpri = document.getElementById("price1").value;
var pri = fpri.substr(1);
var qty = document.getElementById("quantity1").value;
var spri = document.getElementById("price2").value;
var pri2 = spri.substr(1);
var qty2 = document.getElementById("quantity2").value;
if (document.getElementById("circle").checked)
{
document.getElementById("total").value ='$' + Number(pri) *
Number(qty);
}
else
document.getElementById("total").value = '$' + Number(pri2) *
Number(qty2);
}
</script>
</head>
<body>
<table border = "1">
<tr>
<td> <input type="checkbox" id="circle" /> Circle </td>
<td> <img src="circle.jpg"> </img> </td>
<td> Price: <input type="text" size="4" value = "$10.00"
id="price1" name = "price1" /></td>
<td> Quantity: <input type="text" size = "4"
id="quantity1"/></td>
</tr>
<tr>
<td> <input type = "checkbox" id="stickman" /> Stickman </td>
<td> <img src = "stickman.gif"> </img> </td>
<td> Price: <input type="text" size="4" value = "$5.00"
id="price2" /> </td>
<td> Quantity: <input type="text" size="4" id="quantity2" />
</td>
</tr>
</table>
<br />
<input type = "button" value = "Add to cart"
onclick="createCookie()">
<br />
<br />
<a href ="cart.html" > View Cart </a>
<br />
<input type = "text" size = "8" id = "total" readonly = "readonly"
/> Total
<br />
<input type = "button" id = "calcu" value = "calc" onclick = "Calc
()" />
<input type = "button" value = "retrieve" onclick = "retrieve()" />
<input type = "text" readonly = "readonly" name = "ret" id =
"ret"/>
</body>
</html>
the calculate and retrieve buttons, and the readonly text boxes are there just so i know the cookie is being stored and retrieved, and that i'm able to get the total, which will be displayed on my cart page.
here is the code for my cart page
cart.html
<html>
<head>
<title> Cart </title>
<h1> My cart </h1>
<script type = "text/javascript">
function retr(circle)
{
document.getElementById("q2").value = document.getElementById("quantity1").value
}
function retrieve()
{
var quvalue = retr("circle")
if (quvalue != false) {
document.getElementById("q2").value = quvalue
}
document.getElementById("ret").value = document.cookie;
}
</script>
</head>
<body onload = "retrieve()">
<table border = "1">
<td>Stickman </td>
<td><input type = "text" size = "8" id = "q2" readonly = "readonly" /></td>
<td id ="p1"> price per </td>
<td id ="t1"> total </td>
<tr> </tr>
<td> Circle </td>
<td> quantity order </td>
<td> price per </td>
<td> total </td>
<tr> </tr>
<td colspan = "3"> TOTAL: </td>
<td> total price </td>
</table>
<br /> <br />
<input type ="text" id = "ret" readonly = "readonly" />
<br / > <br />
<input type = "button" value = "Checkout">
<br /> <br />
<a href = "store.html" > Continue Shopping </a>
</body>
</html>
the values that are supposed to be retrieved in the table are invoked using the onload event attribute which is suppose to call the retrieve() function.
also, i understand that the way i created the table in my carts page isn't completely correct. but my main focus right now is to get the necessary values to be displayed in my table, then i will go back in rewrite my table code.