Simple javascript unity converter not working - javascript

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.

Related

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>

What have i done wrong in this javascript calculation?

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

Javascript replace string with values from dom object

Im trying to make a formula dynamic and also the input fields. First problem is to change the (c1 + d2) into values like (1 + 2) depending on what is the value in input. consider that tdinput is dynamic so I can add as many as I can and formula can change anytime.
<input class="tdinput" type="text" data-key="c1">
<input class="tdinput" type="text" data-key="d2">
<input type="text" data-formula="(c1 + d2)">
<script>
$('.tdinput').on('change', function() {
var key = $(this).attr('data-key');
$('[data-formula*="+key+"]').each(function() {
//now here goes to change the data-formula by inputted values
//calculate using eval()
});
});
</script>
You need to make a more modular approach with this.
And make good use of the javascript jquery api you're using.
When a variable is defined by data-something-something you can access it by jQuerySelectedElement.data('something-something')
Now, eval is evil, but when you sanitise your input variables(in this case by parseInt) you should be relatively save from xss inputs etc..
What happens is, all the variables are inserted as an property in an object t.
then eval will call and and access all the objects in t and do the calculation.
Only requirement is that you define all the variables not as just c2, but as t.c2 in your key definition properties.
have a look below at the play with the data properties and the eval.
When using eval ALWAYS make sure you only eval 'safe' data! Don't eval strings if you plan to safe user input! you open your site for XSS attacks then.
$('[data-formula]').on('keyup', function() {
var $this = $(this);
var formulaName = $this.data('formula');
var $output = $('[data-formula-name="'+formulaName+'"]');
var formula = $output.data('formula-calc');
var t = {};
var keys = [];
$select = $('[data-formula="'+formulaName+'"]');
$select.each(function(index,elem) {
var $elem = $(elem);
var key = $elem.data('key');
t[key] = parseFloat($elem.val());
keys.push(key);
if(isNaN(t[key])) {
t[key]=0;
}
});
for(var c=0;c<keys.length;c++) {
formula = formula.replace(new RegExp(keys[c],'g'),'t.'+keys[c]);
}
var result = 0;
eval('result = '+formula)
$output.val(result)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
sum:
<input class="tdinput" type="text" data-formula="sum" data-key="c1">
<input class="tdinput" type="text" data-formula="sum" data-key="d2">
<input type="text" data-formula-name="sum" data-formula-calc="(c1 + d2)" disabled>
<BR/>
xor
<input class="tdinput" type="text" data-formula="pow" data-key="c1">
<input class="tdinput" type="text" data-formula="pow" data-key="d2">
<input type="text" data-formula-name="pow" data-formula-calc="(c1 ^ d2)" disabled>
<BR/>
sub
<input class="tdinput" type="text" data-formula="sub" data-key="c1">
<input class="tdinput" type="text" data-formula="sub" data-key="d2">
<input type="text" data-formula-name="sub" data-formula-calc="(c1 - d2)" disabled>
<BR/>
silly
<input class="tdinput" type="text" data-formula="silly" data-key="c1">
<input class="tdinput" type="text" data-formula="silly" data-key="d2">
<input type="text" data-formula-name="silly" data-formula-calc="(c1 / d2 * 3.14567891546)" disabled>
You can use eval().
Logic
Fetch formula and save it in string
Get all valid keys
Replace keys with value in formula
Use eval() to process it
Sample
JSFiddle
$("#btnCalculate").on("click", function() {
var $f = $("input[data-formula]");
var formula = $f.data("formula");
formula.split(/[^a-z0-9]/gi)
.forEach(function(el) {
if (el) {
let v = $("[data-key='" + el + "']").val();
formula = formula.replace(el, v);
}
});
var result = eval(formula);
console.log(result)
$f.val(result)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input class="tdinput" type="text" data-key="c1">
<input class="tdinput" type="text" data-key="d2">
<br/>
<input type="text" data-formula="(c1 + d2)">
<button id="btnCalculate">calculate</button>
Reference
Eval's alternate for string calculation.
Why using eval is not a good idea

how to pass calculated values using javascript

the following values are to calculate the user entered values, these are calculated and passed to the text field,
if(computer && monitor && tv && laptop && cell)
{ // getting the text field the values and calculated
var valueCom = document.getElementById("computer").value ;
var valueMon = document.getElementById("monitor").value ;
var valueTv = document.getElementById("tv").value ;
var valueLap = document.getElementById("laptop").value ;
var valueCel = document.getElementById("cell").value;
var finalCom = valueCom * 0.1818937134 ;
var finalMon = valueMon * 0.056842 ;
var finalTv = valueTv * 0.056842 ;
var finalLap = valueLap * 0.090947 ;
var finalCel = valueCel * 0.045473 ;
var totalTonnes = finalCom + finalMon + finalTv + finalLap + finalCel;
var totalCarbon = totalTonnes * 1 ;
var totalTree = totalTonnes * 17.1969 ;
var totalPetrol = totalTonnes * 286.396 ;
var totalPlastic = totalTonnes * 646.421 ;
// pass this above four values to the textfield
}
<input type="text" name="carbon" >
<input type="text" name="tree" >
<input type="text" name="petrol" >
<input type="text" name="plastic" >
// field to pass values here
how to pass this values using java script to the text field. can anyone help me please
you want to add id to text field,
<input type="text" name="carbon" id="carbon">
<input type="text" name="tree" id="tree">
<input type="text" name="petrol" id="petrol">
<input type="text" name="plastic" id="plastic">
then after javascript,
document.getElementById("carbon").value=totalCarbon;
document.getElementById("tree").value=totalTree;
document.getElementById("petrol").value=totalPetrol;
document.getElementById("plastic").value=totalPlastic;
and also you can use to value set by name,
document.getElementsByName("plastic")[0].value = totalPlastic;
......
or,
document.getElementById("plastic").setAttribute('value',totalCarbon);
.....
Assign your resultant text field with id="result" or anything. Then, you can put your result as $(#result).val(yourCalcultedResult);
set the value property
document.getElementById("carbon").value = totalCarbon;
document.getElementById("tree").value = totalTree;
document.getElementById("petrol").value = totalPetrol;
document.getElementById("plastic").value = totalPlastic;
and set the ids to the respective elements
<input type="text" name="carbon" id="carbon" >
<input type="text" name="tree" id="tree" >
<input type="text" name="petrol" id="petrol" >
<input type="text" name="plastic" id="plastic" >
Or if you still want to use names only, then make it
document.getElementsByName("carbon")[0].value = totalCarbon;
document.getElementsByName("tree")[0].value = totalTree;
document.getElementsByName("petrol")[0].value = totalPetrol;
document.getElementsByName("plastic")[0].value = totalPlastic;
document.getElementsByName("carbon")[0].value = totalCarbon;
document.getElementsByName("tree")[0].value = totalTree;
document.getElementsByName("petrol")[0].value = totalPetrol;
document.getElementsByName("plastic")[0].value = totalPlastic;
If your controls are in a form, like:
<form>
<input type="text" name="carbon">
<input type="text" name="tree">
<input type="text" name="petrol">
<input type="text" name="plastic">
...
</form>
then you can get a reference to the form and access them as named properties of the form, e.g.
var form = document.forms[0];
form.carbon.value = totalCarbon;
form.tree.value = totalTree;
...
Just make sure you don't give form controls a name that is the same as a form property, like submit or name, as these will shadow the form's default properties of the same name (so you can't call form.submit() or access the form's name, if it has one).
//globally i declared carbon, tree, petrol, plastic
document.getElementById("carbon").value = carbon ;
document.getElementById("tree").value = tree ;
document.getElementById("petrol").value = petrol ;
document.getElementById("plastic").value = plastic ;

Count values from <input type="text"

Hello i want to count the ids inside a input type="text"
the values return as this 1,4,6 etc
<input type="hidden" class="selected_ids" value="selected_ids" name="selected_ids[]" multiple="yes" id="selected_ids" />
here the only javascript version :
var testme = function() {
var myInput = document.getElementById('selected_ids');
var myValue = myInput.value;
var myCount = myValue.split(',').length;
document.body.innerHTML += '<br>myValue = ' + myValue + ' | myCount = ' + myCount;
}
<input type="text" class="selected_ids" value="1,4,6" name="selected_ids[]" multiple="yes" id="selected_ids" />
<button onclick='testme()'>test me</button>
You can use split function. for example :
var curval = document.getElementById('selected_ids').value;
var curval_arr = curval.split(',');
var cnt = curval_arr.length;
First, your input type needs to be text and not hidden. It's not possible to enter values in a hidden text box.
So your text box should be :-
<input type="text" class="selected_ids" value="selected_ids" name="selected_ids[]" multiple="yes" id="selected_ids" />
Now suppose the user enters 1,4,6 into the text box(make sure the numbers are separated by a comma). Then on the PHP side you can access as follows.
<?php
$array = explode(',', $_POST['selected_ids']); //this array consists all the elements.
//To get length, do :-
count($array);
?>

Categories

Resources