I created a Bitcoin (BTC) to Canadian Dollar (CAD) converter that uses the current price from a different site, now I am trying to limit the values acceptable for the BTC/CAD inputs but it doesn't work.
The limits I want to set is $2 to $99.99 for CAD and the BTC equivalent for max/min but it doesn't want to work...
Fiddle:
https://jsfiddle.net/z735tswj/ all the relevant code is in the html tab or below
<input id="btcc" type="text" onkeyup="btcConvert()" onchange="btcCheck()">BTC</input>
<input id="cadc" type="text" onkeyup="cadConvert()" onchange="cadCheck()">CAD</input>
<br>
<br>
<script>
function btcConvert() {
var btc = document.getElementById("btcc").value;
var btcCalc = btc * price;
var btcCalc = btcCalc.toFixed(2);
document.getElementById("cadc").value = btcCalc;
btcCheck();
}
function cadConvert() {
var cad = document.getElementById("cadc").value;
var cadCalc = cad / price;
var cadCalc = cadCalc.toFixed(8);
document.getElementById("btcc").value = cadCalc;
cadCheck();
}
function btcCheck() {
if (btc.value < 0.001649) btc.value = 0.001649;
if (btc.value > 0.082259) btc.value = 0.082259;
btcConvert();
}
function cadCheck() {
if (cad.value < 2) cad.value = 2;
if (cad.value >= 100) cad.value = 99.99;
cadConvert();
}
</script>
Got it working, your script was not passing the input value to cadCheck()
I just made a few edits to get it to work. cadCheck() will get the value of the input before running cadConvert().
function cadCheck(input) {
if (input.value < 2) input.value = 2;
if (input.value >= 100) input.value = 99.99;
cadConvert();
}
I also took out the onkeyup="cadConvert() because you are calling that in cadCheck() and added this("this" being the input's value) to onchange="cadCheck().
new html <input id="cadc" type="text" onchange="cadCheck(this)">CAD</input>
Here is my code https://jsfiddle.net/so7s9efr/
Don't mean to be the "just use this" guy, but currency conversion is a common, solved problem and there are many good solutions out there.
A good one is money.js
Was working on a fiddle solution, but Paul Allen's works fine.
Related
I am trying to do one task using javascript, i have two text boxes one is for total amount and second is for discount and i have value in total amount for example 100 and when i insert discount in discount text box that inserted discount must be subtract from total amount but when i remove that discount that value must be as previous i tried below but it substract value but when it removes discount it does not work please help. Thanks in advance.
$(".form-basic .grand-discount").on('keyup', function () {
var gross= $('input[name="total_gross_amount"]').val();
var totalDiscount = $(this).val();
if(totalDiscount != '')
{
var total=gross-totalDiscount;
}
else{
var total=gross+totalDiscount;
}
$('input[name="total_gross_amount"]').val(total);
});
$(".form-basic .grand-discount").on('keyup', function () {
var gross= $('input[name="total_gross_amount"]').val();
var totalDiscount = $(this).val();
if(totalDiscount.length>0) {
var total=gross-totalDiscount;
} else{
var total=gross;
}
$('input[name="total_gross_amount"]').val(total);
});
Try this one.
As #Chris G proposed in comments and I edited his fiddle(just an example how this could be done, but since the questioner did not provide all info, this is what we have done):
$(".form-basic input").on('input', function() {
var gross = $('input[name="total_gross_amount"]').val();
var totalDiscount = $('.grand-discount').val();
var total = gross - totalDiscount;
$('#total').html(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-basic">
<input type="number" class="total_gross_amount" name="total_gross_amount">
<input type="number" class="grand-discount" name="grand-discount">
</form>
<p>Total: <span id="total"></span></p>
I think this solve your problem, the key is to take gross out of input event:
$(document).ready(function(){
var gross= $('input[name="total_gross_amount"]').val();
$(".form-basic .grand-discount").on('keyup', function () {
var totalDiscount = $(this).val();
if(totalDiscount != '')
{
var total=gross-totalDiscount;
}
else{
var total=gross+totalDiscount;
}
$('input[name="total_gross_amount"]').val(total);
});
});
ful example here https://jsfiddle.net/wkj0jjvp/
if you want to update gross amount, you should set an event for gross and put inside the discount event.
<form>
<input type="text" name="" value="">
</form>
//for loop used to calculate balance after payment(x) and interest
// the variable I want defined from the form input box
for(i = 6000; i>=10; i = i * (1+0.2/26)-x){
var x = 155;
document.write("Balance " + " $" + i + "<br/><br/>");
}
You could attach a pseudo class in your input element and then get the value inserted like below:
<input type="text" name="" value="" class="js-interest">
<script>
var ele = document.getElementsByClassName("js-interest")[0];
var value = parseFloat(ele.value);
</script>
You can try document.getElementById('input_id').value and then use parseInt to get it as an integer, as below:
var x = parseFloat(document.getElementsByName('number_box').value);
Also, the html must look something like this:
<form>
<input type="text" name="number_box" value="">
</form>
Optionally, instead of document.getElementsByName() you can use document.getElementById() or document.getElementsByClassName().
Update:
If I am not wrong
for(i = 6000; i>=10; i = i * (1+0.2/26)-x){
var x = 155;
document.write("Balance " + " $" + i + "<br/><br/>");
}
It seems like you are writing to the DOM inside a for loop don't do that calculate your ANS and then write to the DOM.
Also, don't read the data from input inside the loop. (You will be repeatedly reading and writing the data thats not good.)
Your for loop for(i = 6000; i>=10; i = i * (1+0.2/26)-x) is incrementing using some expression i = i * (1+0.2/26)-x (make sure it is bound to the condition and its not making the loop infinite)
You can select the value from the input field using the following code
x = parseInt(document.querySelector('form input[name="my_number"]').value);
document.querySelector it uses CSS style selector. So, to select the input field inside your form. I have added a name to the form as name="my_number"
<input type="text" name="my_number" value="">
now using the css selector form input[name="my_number"] it select the input field inside a form with name "my_number"
The whole Query selector that will return the input element is this,
document.querySelector('form input[name="my_number"]')
now to get the value of the input field you have to read the value property of the input field.
document.querySelector('form input[name="my_number"]').value
This will return your input value as string.
Now, we need to parse that string value to a Integer format.
We do that like this, (using parseInt)
parseInt(document.querySelector('form input[name="my_number"]').value)
I have added you code in a function named calc
function calc() {
var x = parseInt(document.querySelector('form input[name="my_number"]').value);
var ans= calculate_your_value(x);
document.write("Balance " + " $" + ans + "<br/><br/>");
}
I have fetched the answer from a function named get calculated answer and its good to do this way.
function calculate_your_value(x){
// calculate the ans the for loop seems buggy
//for (i = 6000; i >= 10; i = i * (1 + 0.2 / 26) - x) {}
return x; //dummy ans
}
It is called when you submit the form.
To do that I have added onsubmit='calc()' on your form tag.
<form onsubmit='calc()'>
Additionally, I have added this function that submits the form when you have pressed enter too (Just for fun) :)
document.onkeydown=function(){
if(window.event.keyCode=='13'){
calc();
}
}
It just listens for key down press and check if it is a enter key (keycode is 13)
and calls the same calc function.
function calc() {
var x = parseInt(document.querySelector('form input[name="my_number"]').value);
var ans= calculate_your_value(x);
document.write("Balance " + " $" + ans + "<br/><br/>");
}
document.onkeydown = function() {
if (window.event.keyCode == '13') {
calc();
}
}
function calculate_your_value(x){
// calculate the ans the for loop seems buggy
//for (i = 6000; i >= 10; i = i * (1 + 0.2 / 26) - x) {}
return x; //dummy ans
}
<form onsubmit='calc()'>
<input type="text" name="my_number" value="">
<input type="submit" id="submitbtn" />
</form>
Pretty new to this Javascript thing.
I want to change a Javascript variable when a user inserts a number into an input field in my HTML document and clicks a button.
I'm assuming you'd use a function, but how do you gather the data and change the variable?
The stuff I tried to make looks a little something like this.
HTML
<input type="number" id="inputField">
<button onclick="changeTheVariable()" type="button" id="pushMe"></button>
Javascript
var a = 0;
function changeTheVariable() {
a = document.getElementById("inputField").value;
}
but it's not working!
Edit 1:
Wow. I didn't think I'd get this kind of attention. I also found it a bit strange it didn't work at first.
The question I'm asking is partly for a calculator here: https://titomagic.com/debug
It's simple, you type in a number, click the button and it calculates (based on other variables) to a result on the bottom.
Here's a link to the Javascript file, if you wanna have a look: https://titomagic.com/js/bursdagskalkulator.js
To those of you asking; yes, I've been testing with a console.log and the variable is not changing. It's not affecting the other variables (as it should?).
Also I've never heard of JSfiddle.
I discovered few things in the summarizeGjester() function. First of all I moved all the Javascript code in the bursdagskalkulator.js file inside the summarizeGjester() function. Also I converted var antallGjester to integer using parseInt() function, because it was treated as string before.
var antallGjester = document.getElementById("gjesterAntallInput").value;
antallGjester = parseInt(antallGjester); //integer conversion
Also the first Boolean comparison was changed to
if ((antallGjester < 10) && (antallGjester > 0)), so that the second one would work if there’s 0 value: else if (antallGjester === 0).
function summarizeGjester() {
var antallGjester = document.getElementById("gjesterAntallInput").value;
antallGjester = parseInt(antallGjester);
var fastPris = 1500;
var fastPrisDifferanse = 10;
var gjestePris = 120;
var gjesteDifferanse = antallGjester - fastPrisDifferanse;
var gjesteSum = gjestePris * gjesteDifferanse;
var gjesterTotalt = 0;
if ((antallGjester < 10) && (antallGjester > 0)) {
console.log("antallGjester < 10");
gjesterTotalt = 1500;
} else if (antallGjester === 0) {
console.log("antallGjester === 0");
gjesterTotalt = 0;
} else {
console.log("else");
gjesterTotalt = fastPris + gjesteSum;
}
document.querySelector('#results').innerHTML = gjesterTotalt;
}
<form>
<div class="form-group">
<label for="gjesterAntall">Antall barn:</label>
<input type="number" class="form-control" id="gjesterAntallInput">
</div>
<button class="btn btn-lg btn-warning" onclick="summarizeGjester()" type="button" id="sumGjester">Legg sammen</button>
</form>
<h1 class="text-center" style="font-size:80px;"><strong><span id="results">0</span>,-</h1>
I hope this helps :-)
HTML
<input type="number" id="inputField" ClientIDMode="static">
<button onclick="changeTheVariable()" type="button" id="pushMe"></button>
Javascript
var a = 0;
function changeTheVariable() {
a = document.getElementById('inputField').value;
alert(a);
}
Use Static ClientIDMode for stable id and access after page rendering
PlaceHolders canh change childe's id
I suppose this will work for you
var a = 0;
function changeTheVariable() {
a = document.getElementById("inputField").value || a;
document.getElementById("result").innerText = parseFloat(a);
}
<input type="number" id="inputField">
<button onclick="changeTheVariable()" type="button" id="pushMe">Click me</button>
<div>Result: <span id="result"></span></div>
Edited:
The reason behind this code is not running in jsfiddle is here.
After making the changeTheVariable() global variable this code will work in jsfiddle also. Here https://jsfiddle.net/1b9cfmje/
Use the following javascript code:
window.onload = function(){ var a = 0; window.changeTheVariable = function() { a = document.getElementById("inputField").value || a; document.getElementById("result").innerText = parseFloat(a); }}
when user select any option in radio buttons in group one and then enter any number in respective input field and then select the next any radio option and enter any value in input field then this time it should add the new result with old one and display it in result input field and now if he empty any input field then that should also minus from the total result and display it in result field.
i have so many groups like that but here i just put two of them to get the result.
here id the FIDDLE
here is the jquery code. i can work in jquery but not very good i used separate code for every group and i know there must be a way to get this whole functionality through generic code but again i am not good at jquery
jQuery("#txt_im").keyup(setValue);
jQuery('[name="rdbtn-im"]').change(setValue);
function setValue() {
var txt_value = jQuery("#txt_im").val();
var rad_val = jQuery('[name="rdbtn-im"]:checked').val();
if(!txt_value.length) {
jQuery('#final_res').val('');
return;
}
if (!rad_val.length) return;
var res = txt_value * rad_val;
var final = parseInt(res, 10);
var MBresult = final / 1024;
jQuery('#final_res').val(MBresult.toFixed(2));
}
var final2 = 0;
jQuery("#txt_fb").keyup(setValue2);
jQuery('[name="rdbtn-fb"]').change(setValue2);
function setValue2() {
var txt_value = jQuery("#txt_fb").val();
var rad_val = jQuery('[name="rdbtn-fb"]:checked').val();
if(!txt_value.length) {
jQuery('#final_res').val('');
return;
}
if (!rad_val.length) return;
var res2 = txt_value * rad_val;
final2 = parseInt(res2, 10) + final;
var MBresult = final2 / 1024;
jQuery('#final_res').val(MBresult.toFixed(2));
}
infact user is free to select any number of groups or also free to remove any number of group after selection.
i know there is error in fiddle when user select 2nd group after the select of first it removes the result which is wron and i tried to solve it but failed but i define the whole seen what i need to do. i will be very thankfull to you for this kind favour.
HTML:
<table>
<tr>
<td>
<input type="radio" name="rdbtn-im" id="rdbtn-im-day" value="25" class="rdbtn-style-social" />Daily
<input type="radio" name="rdbtn-im" id="rdbtn-im-week" value="175" class="rdbtn-style-social" />Weekly
<input type="text" name="txb3" id="txt_im" class="txt-email" style="width:100px;margin: 2px;" />
</td>
</tr>
<tr>
<td class="sec-td-rdbtns-social">
<input type="radio" name="rdbtn-fb" id="rdbtn-fb-day" value="3500" class="rdbtn-style-social" />Daily
<input type="radio" name="rdbtn-fb" id="rdbtn-fb-week" value="500" class="rdbtn-style-social" />Weekly
<input type="text" name="txb1" id="txt_fb" class="txt-email" style="width:100px;margin: 2px;" /> </td>
</tr>
</table>
<br>result
<input type="text" name="final_res" id="final_res" class="" style="width:100px;margin: 2px;" />
Jquery:
jQuery(".txt-email").keyup(setValue);
jQuery('.rdbtn-style-social').change(setValue);
function setValue() {
var total = 0;
$(".rdbtn-style-social:checked").each(function () {
var myInput = $(this).siblings(".txt-email").val();
if (myInput.length) {
total += myInput * $(this).val();
}
});
if (total) {
jQuery('#final_res').val((total / 1024).toFixed(2));
} else {
jQuery('#final_res').val('');
}
}
FIDDLE
If you are using chrome, then console is your best friend ( https://developers.google.com/chrome-developer-tools/docs/console )
For firefox you have firebug, opera has dragonfly (or something like that ?). Even IE has console now. There you can see all errors popping up.
Ok, so first of all let's clean up this a little bit by wrapping it all in closure (we can now safely use the $ instead of jQuery even if there is namespace conflict outside). Also, we will use single function for both cases, because they are so similar.
!function ($) {
$(".txt-email").keyup(setValue);
$('.rdbtn-style-social').change(function(e) { setValue(e, true) });
function setValue(e, radio) {
if('undefined' === typeof radio) radio = false;
var attr = radio ? 'name' : 'id';
var tmp = e.target[attr].split('-');
var media = tmp[tmp.length - 1];
var txt_value = $("#txt-"+media).val();
var rad_val = $('.rdbtn-style-social[name="rdbtn-'+media+'"]:checked').val();
if (!txt_value.length || !rad_val.length) {
$('#final_res').val('');
return false;
}
var res = (txt_value | 0) * rad_val;
var final = parseInt(res, 10);
var MBresult = final / 1024;
$('#final_res').val(MBresult.toFixed(2));
}
}(jQuery);
(variable | 0 is same as parseInt(variable, 10)).
So, long story short: when radio or text gets changed, the function is fired (if it's radio, additional argument is passed). We retrieve whether we want to work on im or fb, then do whatever you want. I changed id of inputs to replace _ with -'s (for split consistency)
Final jsfiddle: http://jsfiddle.net/Misiur/f6cxA/1/
Preamble: I'm more of a PHP/MySQL guy, just starting to dabble in javascript/jQuery, so please excuse this dumb newbie question. Couldn't figure it out from the Docs.
I have a form without a submit button. The goal is to allow the user to input values into several form fields and use jQuery to total them up on the bottom in a div. The form kinda looks like this but prettier:
<form>
Enter Value: <input class="addme" type="text" name="field1" size="1">
Enter Value: <input class="addme" type="text" name="field2" size="1">
Enter Value: <input class="addme" type="text" name="field3" size="1">
etc.....
<div>Result:<span id="result"></span></div>
</form>
Is it possible to add these up? And if so, can it be done anytime one of the input fields changes?
Thanks.
UPDATE:
Brian posted a cool collaborative sandbox so I edited the code to look more like what I have and it's here:
http://jsbin.com/orequ/
to edit go here:
http://jsbin.com/orequ/edit
Sticking this right after the </form> tag should do it:
<script>
function displayTotal() {
var sum = 0
var values = $('.addme').each(function(){
sum += isNaN(this.value) || $.trim(this.value) === '' ? 0 : parseFloat(this.value);
});
$('#result').text(sum);
}
$('.addme').keyup(displayTotal);
</script>
Here's a demo: http://jsbin.com/iboqo (Editable via http://jsbin.com/iboqo/edit)
Any non numeric or blank values will be disregarded in the calculation (they'll be given a value of zero and hence not affect the sum).
function sumValues() {
var sum = 0;
$("input.addme").each(function(){
var $this = $(this);
var amount = parseInt($this.val(), 10);
sum += amount === "" || isNaN(amount)? 0 : amount;
});
$("#result").text(sum);
}
$(function() {
sumValues();
$("input.addme").keyup(function(){
sumValues();
});
});
Working Demo
(function(){
var context = $("form"), elements = $("input.addme", context);
function getSum(elements) {
var sum = 0;
$(elements, context).each( function() {
var v = parseInt(this.value);
v === parseInt(v,10) ? sum += v : sum = sum;
})
return sum;
}
$(elements).bind("keyup", function() {
$("#result").text( getSum(elements) );
});
})();
isolated scope and context, included dealing with non-integer values, function getSum should rather return a value than do something itself.
Try this:
$(".addme").bind("change",function(){
var _sum = 0;
$(".addme").each(function(i){
_sum += parseInt($(this).val());
});
$("#result").val(_sum);
});