What have i done wrong in this javascript calculation? - javascript

I have two inputs that can hold a value and where a value is typed in.
calculate() kinda do the job but I getting an error in the console :
Uncaught TypeError: Cannot set property 'value' of null(…)
But for calculate() I get only that error!
if($sal>10){
echo '<td>
<input type="text" oninput="calculate()" name="monthly_sum_019" id="monthly_sum_019" value="">
<input type="hidden" class="input toggle all" id="monthly_sum_019" oninput="calculate()" value="" placeholder="'.$sal.'"></td>';
}else{
echo '<td>
<input type="text" oninput="calculate()" name="monthly_sum_019" id="" value="">
<input type="hidden" class="input toggle all" id="monthly_sum_019" oninput="calculatez()" value="'.$sal.'"></td>';
}
And have 2 inputs that returns result of calculation:
if($sal>10){
echo '<td>
<input type="text" id="result" name="reward_019" value=""></td>';
}else{
echo '<td>
<input type="text" id="result2" name="reward_019" value=""></td>';
}
And the javascript:
<script>
function calculate() {
var myBox1 = parseFloat(document.getElementById('monthly_sum_019').value);
var myBox2 = parseFloat(document.getElementById('norm').value);
var myBox3 = parseFloat(document.getElementById('time_hours_019').value);
var result = document.getElementById('result');
var myResult = (myBox1 / myBox2) * myBox3;
result.value = myResult.toFixed(2);
}
</script>
<script>
function calculatez() {
var myBox1 = parseFloat(document.getElementById('hourmoney').value);
var myBox3 = parseFloat(document.getElementById('time_hours_019').value);
var result2 = document.getElementById('result2');
var myResult = myBox3 * myBox1;
result2.value = myResult.toFixed(2);
}
</script>
What is wrong?

Usually Cant do something of NULL means you try to select element but it's not presented in DOM.
I see that you try to select element with ID result2 but in your provided code I see that when $sal > 10 == true you do not put element with such ID.
Since it's PHP code you can have same ID in both if and else parts (but not in same part multiple times).

Related

Simple javascript unity converter not working

I'm trying to get a simple converter to work. None of the input fields work at the moment.
Can I get the price variable like I did through PHP?
<h1 style='font-size:46px'>1 DOLLAR = <p id="currentprice" type="number"><?php $url = "https://api.fixer.io/latest?base=USD"; $json = file_get_contents($url); $json_data = json_decode($json, true); $price = $json_data["rates"]["BRL"]; echo $price; ?></p></h1>
How many Dollars?
<input oninput='finalAmountUSD()' onchange='finalAmountUSD()' style='font-size:23px;height:45px' type='number' class="buy buyinput form-control" id='usdamount' required value='0.00000000' tabindex="1" />
How many BRL?
<input oninput='finalAmountBRL()' onchange='finalAmountBRL()' style='font-size:23px;height:45px' type='number' class="buy buyinput form-control" id='brlamount' required value='0.00' tabindex="2" />
<script>
function finalAmountUSD()
{
x = document.getElementById('currentprice').value;
y = document.getElementById('usdamount').value;
z = document.getElementById('brlamount').value;
document.getElementById('usdamount').value = x * z;
}
function finalAmountBRL()
{
x = document.getElementById('currentprice').value;
y = document.getElementById('usdamount').value;
z = document.getElementById('brlamount').value;
document.getElementById('brlamount').value = x * y;
}
</script>
Try this simple example and use to your end.
<script>
//# <-- access with id
//. <-- access with a class name
var value1 = $("#currentprice").html(); // get values from html object
var value2 = $("#currentprice2").val(); // get values from input
alert("Value: "+value1);
</script>
Don't repeat id name or you will have errors.
function finalAmountUSD()
{
x = parseFloat(document.getElementById('currentprice').value);
z = parseFloat(document.getElementById('brlamount').value);
document.getElementById('usdamount').value = x * z;
}
function finalAmountBRL()
{
x = parseFloat(document.getElementById('currentprice').value);
z = parseFloat(document.getElementById('usdamount').value);
document.getElementById('brlamount').value = x * z;
}
<h1 style='font-size:46px'>1 DOLLAR = <input id="currentprice" type="number" value="0.7">BRL</p></h1>
How many Dollars?
<input onblur='finalAmountBRL()' style='font-size:23px;height:45px' type='number' class="buy buyinput form-control" id='usdamount' required value='0.00000000' tabindex="1" />
<br/>
How many BRL?
<input onblur='finalAmountUSD()' style='font-size:23px;height:45px' type='number' class="buy buyinput form-control" id='brlamount' required value='0.00' tabindex="2" />
Your problem is that you are trying to get value from
<p id="currentprice" type="number"></p>
in your code
x = document.getElementById('currentprice').value;
currentprice is a p and cannot have value. Try to change it with a readonly input
One more suggestion: since money value is not integer you better use parseFloat on all your results. Also, I think that you need to use use functions only onblur event.

I cannot connect javascript function with html <input> tags and onclick doesn't work

Hi I am working on a website and i stumbbled across an annoying thing. I cannot, for the love of anything, get to work my form to be able to do some maths and insert them into tag.
P.S nothing works for me, even GetElementsById... or other callouts :(
<script type="text/javascript">
function price(this.form){
var amount = form.elements[1].value;
var gold_price = 0.17;
var price_calc = 0;
price_calc = (amount/gold_price) + " M";
window.alert("price_calc");
form.elements[5].value = price_calc;
}
</script>
//this is input that i would like to get a number to work with in the function
<div>
<input type="text" id="amount" value="10" onchange="price(this.form)" onclick="price(this.form)" maxlength="4" required/>
</div>
//this is input I would like to write in in after function is done functioning :)
<input type="text" id="total_price" placeholder="Total:"/>
thanks for any help in advance.
thanks again,...
Declare your price function to receive an input parameter. Actually this.form as parameter is an invalid statement and leads to an error.
Instead pass this (inside your on* property) and select the input value.
// select #total_price
const totalPrice = document.getElementById( 'total_price' );
function price( input ) {
// Convert value to a number
var amount = +input.value;
var gold_price = 0.17;
var price_calc = 0;
price_calc = ( amount / gold_price ) + " M";
totalPrice.value = price_calc;
}
<input type="text" id="amount" value="10" oninput="price( this )" onclick="price( this )" maxlength="4" required/>
<br>
<input type="text" id="total_price" placeholder="Total:" />
This code working:
<input type="text" value="10" oninput="price(this)" maxlength="4" />
<input type="text" id="total_price" placeholder="Total:" />
<script>
function price(el){
var amount = parseInt(el.value);
var gold_price = 0.17;
var price_calc = (amount / gold_price) + " M";
window.alert("Total: " + price_calc);
document.getElementById('total_price').value = "Total: " + price_calc;
}
</script>

get the quotient of two textbox which has an onChange event

I get the sum of ua and ub and display on tu textbox. I multiplied the ua
and ga textbox and display on uu textbox as well as the ub ang gb . Get
the sum of uu and a and display on tt textbox. I want to get the quotient
of tt and tu and display on gpa textbox but it doesnt work. Please help.
Thanks in advance.
function sum(){
var ua = document.getElementById('ua').value;
var ub = document.getElementById('ub').value;
var result = parseInt(ua) + parseInt(ub);
if (!isNaN(result)) {
document.getElementById('tu').value = result;
document.getElementById('tu').dispatchEvent(new Event('change'));
}
}
function suma(){
var ua = document.getElementById('ua').value;
var ga = document.getElementById('ga').value;
var result = parseInt(ua) * parseInt(ga);
if (!isNaN(result)) {
document.getElementById('uu').value = result;
document.getElementById('uu').dispatchEvent(new Event('change'));
}
}
function sumb(){
var ub = document.getElementById('ub').value;
var gb = document.getElementById('gb').value;
var result = parseInt(ub) * parseInt(gb);
if (!isNaN(result)) {
document.getElementById('a').value = result;
document.getElementById('a').dispatchEvent(new Event('change'));
}
}
function s(){
var uu = document.getElementById('uu').value;
var a = document.getElementById('a').value;
var result = parseInt(uu) + parseInt(a);
if (!isNaN(result)) {
document.getElementById('tt').value = result;
document.getElementById('tt').dispatchEvent(new Event('change'));
}
}
function g(){
var tt = document.getElementById('tt').value;
var tu = document.getElementById('tu').value;
var result = parseFloat(tt) / parseFloat(tu);
if (!isNaN(result)) {
document.getElementById('gpa').value = result;
}
}
<input type="text" id="ua" name="ua" size="7" onkeyup="sum();">
<input type="text" id="ga" name="ga" size="7" onkeyup="suma();">
<input type="text" id="uu" name="uu" size="7" onchange="s();"/>
<input type="text" id="ub" name="ub" size="7" onkeyup="sum();">
<input type="text" id="ga" name="ga" size="7" onkeyup="sumb();">
<input type="text" id="a" name="a" size="7" onchange="s();"/>
<input type="text" id="tu" name="tu" onchange="g();"/>
<input type="text" id="tt" name="tt" onchange="g();"/>
<label>GPA</label>
<input type="text" id="gpa" />
As far as I can tell, everything in your code works (after your edit), except that you want to get the element with the ID gb in the function sumb, but the element doesn't exist. As you have it now, your code displays the result of the value of tt (second in the HTML) divided by the value of tu (first in the HTML).
That said, I'm still not sure what you mean when you say "it's not working". The only thing I could think of is that you have to take away the focus from the tu or tt input element in order to make the gpa element display the result, because you used onchange instead of onkeyup.
As others have pointed out and as I also want to emphasize is that you should try to give your variables meaningful names. When you look at your code in three years, do you think you will still know what "gpa" and "uu" is?
In the following snippet, I only copied the <input>s that are relevant for the division. I use addEventListener instead of inline event listeners (onkeyup="sumb();") and made it more readable:
var dividendElement = document.getElementById('dividend');
var divisorElement = document.getElementById('divisor');
var resultElement = document.getElementById('result');
function updateQuotient () {
var result = parseFloat(dividendElement.value) / parseFloat(divisorElement.value);
if (!isNaN(result)) {
resultElement.value = result;
}
}
dividendElement.addEventListener('keyup', updateQuotient);
divisorElement.addEventListener('keyup', updateQuotient);
<input type="text" id="dividend">
/
<input type="text" id="divisor"> <!-- <input> elements don't need a closing tag! -->
=
<input type="text" id="result">

how to get two dynamic textbox value in jquery

Thanks in advance, Actually i have a form with two hidden textbox fields one is <input type="hidden" name="item_name" class="course_name" value="<?php echo $cartData['exam'];?>"> and the other is <input type="hidden" name="amount" class="amount" value="<?php echo $priceTotal;?>">, the the value is taken inside the hidden field dynamically from PHP code through loop. So how can i get the dynamic values of "item_name" textbox field and "amount" textbox field in comma seperated using Jquery when clicking the image button with id="placeOrder".
For example like this : for amount-->200,300 and for course name -->PMP,CAPM . I have written some code it will take the values within the jquery each loop but i have to pass through ajax as json format like this data : {cname:course_name,priceBox:textboxVal} so value with comma seperated value should pass through course_name & textboxVal.
My Page is
<html>
<head>
<title></title>
<script>
$(document).ready(function(){
var myArray = [];
$('.amount').each(function(){
var textboxVal = $(this).val();
//alert(textboxVal);
});
var myCourse = [];
//dynamic course name
$('.course_name').each(function(){
var course_name = $(this).val();
//alert(course_name);
});
if(textboxVal!="")
{
$.ajax({
type : "POST",
url : "/invl_exams/cart",
cache : "false",
data : {cname:course_name,priceBox:textboxVal},
success : function(result){
console.log(result);
}
});
}
});
</script>
</head>
</html>
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
<td>
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="shopbusiness#myshop.com">
<input type="hidden" name="upload" value="1">
<?php
if(isset($cartDatas))
{
$itm_no = 1;
$amt = 0;
foreach($cartDatas as $key=> $cartData)
{
$prices = $cartData['price'];
$prd_price = ltrim($prices,'$');
$priceTotal = number_format((float)$prd_price, 2, '.', '');
?>
<input type="hidden" name="item_number" value="<?php echo $itm_no++;?>">
<input type="hidden" name="item_name" class="course_name" value="<?php echo $cartData['exam'];?>">
<input type="hidden" name="amount" class="amount" value="<?php echo $priceTotal;?>">
<input type="hidden" name="shipping" value="shipping Address">
<input type="hidden" name="quantity" value="<?php echo $cartData['orders'];?>">
<?php
$price = ltrim($prices,'$');
$orders = $cartData['orders'];
$amt_Total = $price * $orders;
$amt += $amt_Total;
$amt_Total = number_format((float)$amt, 2, '.', '');
///$amt_Total = round($price * floatval( $orders ),2);
}
?>
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="amount" value="<?php echo $amt_Total;?>">
<?php
}
?>
<input type="image" src="http://www.paypal.com/en_US/i/btn/x-click-but03.gif" name="submit" id="placeOrder">
</td>
</form>
You can do something like following:
$(function(){
var amount = [];
var course = [];
$('.amount').each(function(){
amount.push($(this).val());
});
$('.course_name').each(function(){
course.push($(this).val());
});
console.log(amount.join(',')); //comma seperated value
console.log(course.join(',')) //comma seperated value
});
DEMO
You can use jQuery and attribute selectors to get the value:
var item_name = $('input[name=\'item_name\']').val();
var amount = $('input[name=\'amount\']').val();
var result = item_name + ',' + amount;
Now you can put this in your click handler.
If your inputs are enclosed within form element you can use this serialize the form input values to json object and then pass it to ajax call.
var postData = $("#enclosing_form_elm").serializeObject();
and in your script add reference to serialize object function after jquery
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
Just a demo https://plnkr.co/edit/7maJAUSdakDuvVqXhnzi?p=preview
Thanks to Convert form data to JavaScript object with jQuery

JavaScript function Not Working with onchange attribute of input tag

I have been trying to replicate Duncan Donut Example from HEAD FIRST JAVASCRIPT, but the function subTotal() is never triggered by onchange event and when I look into HTML REFERENCE, I did not find any onchange event in list provided.
Duncan.html
<html>
<head><title>Duncan Online Donut's Service</title></head>
<script type="text/javascript">
function subTotal(){
document.write("working");
const TAXRATE = 0.095;
const DONUTRATE = 0.5;
var tax = 0;
var subTotal = 0;
var total = 0;
var cakedonut = parseInt(document.getElementById("cakedonut").value);
var glazedonut = parseInt(document.getElementById("glazedonut").value);
if(isNaN(cakedonut))
cakedonut = 0;
if(isNaN(glazedonut))
glazedounut = 0;
subTotal = (cakedonut + glazedonut)* DONUTRATE ;
tax = subTotal * TAXRATE ;
total = subTotal + tax ;
document.getElementById("subTotal").value = "$" + subTotal.toFixed(2);
document.getElementById("tax").value = "$" + tax.toFixed(2);
document.getElementById("total").value = "$" + total.toFixed(2);
}
</script>
<body>
<h1><b><i>Duncan Online Donut's Service</i></b></h1>
<form>
Name : <input id="name" type="text" name="name"/><br><br>
#no of cake donuts : <input id="cakedonut" type="text" name="cakedonut" onchange="subTotal()"/><br><br>
#no of glazed donuts : <input id="glazedonut" type="text" name="glazedonut" onchange="subTotal("/><br><br>
subTotal : <input id="subTotal" type="text" name="subTotal" /><br><br>
tax : <input id="tax" type="text" name="tax" /><br><br>
Total : <input id="total" type="text" name="total"/><br><br>
<input type="submit"/><br><br>
</form>
</body>
</html>
JSFiddle
The above is my code. I tried running this on IE and Chrome but in vain. Thanks in advance.
The problem is you have defined a variable and a function both with the same name subTotal and the variable declaration is overriding the function definition. Change the function name to anything say subTotal1 it will work.
JSBIN link
change your function name. don't use subTotal(); and don't use document.write("working");
function subTotalnew()
{
alert('working');
}
onchange="subTotalnew() it gonna be work after input blur.
oninput="subTotalnew() it gonna be work when input entering something.

Categories

Resources