Objective: Looking to build an script which enables 'therm' to be converted to 'MWh'. In order to do so, the user would fill out the 'therm' input box, click the 'convert' button and the 'MWh' value should appear below.
Currently the code I have written is as follows:
<p>Therm: <input type="number" id="thermid" name="therminput" /></p>
<p> MWh: <span id="MWhid"></span></p>
<p><input type="button" value="Submit" id="convertbutton" /></p>
<script>
var therm = document.getElementById("thermid").value; //This identifies the input field for therm
var MWh = therm * 0.029307; //This determines the conversion from therm to MWh - something is wrong here
//Below identifies when the button is clicked (eventlistener) then the 'innerHTML' displays the var MWh in the HTML field
document.getElementById("convertbutton").addEventListener("click", function () {
document.getElementById("MWhid").innerHTML = MWh;
})
</script>
Problem: The result is 0 regardless of the value that the user enters in the 'therm' field and I believe this is resulting from where var MWh is being determined. I don't appear to be able to get this correct. Could someone give me a hand?
Many thanks in advance,
Ralph
You are not updating the calculation every time the button is clicked. The only time the following lines of code are run:
var therm = document.getElementById("thermid").value;
var MWh = therm * 0.029307;
are on the document load. Simply place them inside the event handler, so that their values get updated every time you click the button. I.e.:
document.getElementById("convertbutton").addEventListener("click", function () {
var therm = document.getElementById("thermid").value;
var MWh = therm * 0.029307;
document.getElementById("MWhid").innerHTML = MWh;
})
Related
I am trying to create a function in Javascript which can read an input box line by line and return different values depending on the input.
For example, if someone enters several protein mutations on separate lines with the format Arg86Lys, I want the function to read the first three and last three letters to get Arg Lys. Then, if I have a value stored for Arg Lys (let's say 100), I want the output to be a textbox which prints out the value 100 (and prints out the rest of the values on separate lines).
I am stuck on how to read the input box value line by line, and only extract the first three and last three letters from each line. I also do not understand how I can store values (like Arg Lys = 100) and return said values when a certain input is found.
So far I have created a multiline textbox (in HTML) and tried to make a function that reads line by line:
<body>
<form action = "/cgi-bin/hello_get.cgi" method = "get">
Enter mutations on separate lines with format Arg86Lys
<br>
<textarea rows = "5" cols = "60" name = "description">
</textarea><br>
<input type = "submit" value = "submit" />
</form>
<script>
var lines = document.getElementById('textareaId').innerHTML.split('\n');
for(var i = 0;i < lines.length;i++){
\\
}
</script>
</body>
textarea is an input, so its value is going to be stored in its value property, and passed along with the form submission. Here is an answer I found that goes over how to intercept the submit event for the form:
Intercept a form submit in JavaScript and prevent normal submission
Once you've intercepted the form submission event, pull the value from the description input, and do with it what you want from there
let form = document.getElementById("form");
let data = {"Arg Lys":100}; // store data like this
form.addEventListener("submit",function(e){
e.preventDefault();
var lines = document.getElementById('textareaId').value.split('\n');
document.getElementById('textareaId').value = '';
for(var i = 0;i < lines.length;i++){
let val = lines[i].substring(0,3);
let lastval = lines[i].substring(lines[i].length - 3)
document.getElementById('textareaId').value += val+' '+lastval + ' - ' +data[val+' '+lastval]+'\n';
}
})
<body>
<form id="form" action = "/cgi-bin/hello_get.cgi" method = "get">
Enter mutations on separate lines with format Arg86Lys
<br>
<textarea id="textareaId" rows = "5" cols = "60" name = "description"></textarea><br>
<input type = "submit" value = "submit" />
</form>
</body>
Are you looking for something like that?
So I have this calculator for money that shows you the amount you enter but in a different money value. (Example dollar to euro)
Here is the HTML:
<b> Exchange money </b> <br> <br>
Enter amount for RSD: <input type="number" name="nbsAmount" id="nbsAmount" size="5"> <br>
<button class="dugme">Calculate</button> <br> <br>
Evro value is: <div class="konacnaEvroVrednost"></div>
Dolar value is: <div class="konacnaDolarVrednost"></div>
Swiss value is: <div class="konacnaSwissrednost"></div>
And here is the JS:
$('.dugme').click(function(){
var broj = document.getElementById('nbsAmount').value;
var evro = broj * 0.0085;
var dolar = broj * 0.0095;
var frank = broj * 0.0096;
$('.konacnaEvroVrednost').text(evro + ' €');
$('.konacnaDolarVrednost').text(dolar + ' $');
$('.konacnaSwissrednost').text(frank + ' Fr');
});
And this works fine. As you can see:
Here is the fiddle:
http://jsfiddle.net/5zvdwtpL/1/
But now I want to change this to work a bit more dynamically.
I want there to be two dropdowns that lets you select the value you want to change from to. Like this:
This is what I got so far: https://jsfiddle.net/7s8g9kLt/2/
The problem is that one input value should be copied to the other input value but with the added value of the currency.
So If I select RSD and set 1200, the other USD, then the other input should display 11.4.
So I am stuck a bit here as to how I can achieve this.
First of all, you have bound myFunction to button onClick Event but you have not defined function with this name. You can see following error in console after clicking button
Uncaught ReferenceError: myFunction is not defined
You will have to define this function:
window.myFunction = function() {...}
or event better, add event listener to button click:
document.getElementById('buttonId').addEventListener('click', function() {...})
To calculate dynamic rates, i would first convert input amount to single currency (for example RSD) and then multiply that value by correct rate.
I've modified your jsFiddle (https://jsfiddle.net/rhj4dgz7/3/) to reflect those changes.
You can create a dictionary with the pair of "id" of dropdown and the conversion rate, also you can give the same id to both drop downs. then you gonna just multiply the value by the rate and add the result to the second input.
var rsd = 1;
var evro = 0.0085;
var dolar = 0.0095;
var frank = 0.0096;
var dict = {
"4":rsd,
"1":evro,
"3":dolar,
"2":frank
}
function myFunction(){
var mvs = document.getElementById('mojaVrednostSelect').value;
var nvs = document.getElementById('novaVrednostSelect').value;
var mv = document.getElementById('mojaVrednost').value;
var nv = document.getElementById('novaVrednost').value;
novaVrednost.value = parseInt(mojaVrednost.value) * dict[nvs]
console.log("Yoooo"+ dict[nvs])
console.log("mvs je" + mvs);
console.log("nvs je" + nvs);
console.log("======");
console.log("mojaVrednost je" + mojaVrednost.value);
console.log("novaVrednost je" + novaVrednost.value);
}
document.getElementById('button').onclick = myFunction
check this fiddle
Hope this helps you
I'm trying to make a pen which incorporates the javascript exercises I'm learning. Here is the Pen: https://codepen.io/ychalfari/pen/JVYoNW
In this specific case I'm trying to accept an array from an input and run a function which sums the array when you click the button, and the result should show underneath.
When I click the button I either get an Error: "Bad Path /boomboom/index.html"
or nothing happens the page just kind of reloads and it takes me to the top of the page.
The HTML
<form id="sum-arr-form">
<div class="form-wrap" >
<label for="arr-to-sum"> Enter an Array to sum: <input id="arr-to-sum" class ="med-input" type="text" value = "">
<button class="btn1" onclick ="sumOfArray()">submit</div> </form>
<p>Result: <span id="demo"></span></p>
The Javascript
let inputArr = document.getElementById('arr-to-sum').value;
const add = (a,b) => a+b;
const sumOfArray = function() {
let sum = inputArr.reduce(add);
document.getElementById("demo").innerHTML = sum;};
You have some mistakes in your code.(button tag without type will trigger submit)
<button class="btn1" onclick ="sumOfArray()">submit
change this line to
<input type="button "class="btn1" onclick ="sumOfArray()" value="submit">
then get the value of input inside your sumOfArray function. (add the below 2 lines in your sumOfArray function) (waynelpu's answer above)
let inputArrStr = document.getElementById('arr-to-sum').value;
let inputArr = JSON.parse(inputArrStr);
The value get from input is string, if you want to process it as array you need to convert to correct type in js, try
let inputArrStr = document.getElementById('arr-to-sum').value;
let inputArr = JSON.parse(inputArrStr);
I have a simple html code with form:
<span class="price"></span>
Enter amount:
<input type="text" class="form-control amount" name="amount" value="500">
<!--Next input fields are hidden by Bootstrap class "hide"-->
<input type="text" name="minimal-amount" class="hide minimal-amount" value="500">
<input type="text" name="oneprice" class="hide oneprice" value="0.20">
<script>
$(".amount").on("change", function(){
var am = $(".amount").val();
var min = $(".minimal-amount").val()
if(am<min){
$(".amount").val($(".minimal-amount").val());
}else{
var am = $(".amount").val();
var oneP = $(".oneprice").val();
var finalPrice = am*oneP;
$(".price").html(finalPrice);
}
});
</script>
Idea of this code is very simple. When user put in amount field digits, my script should check, if that, what user put is smaller than minimum available value in minimal-amount field, script changes value of amount field to default minimal-amount.
But the problem is, that id I just add 0 in amount field (and it's value become 5000) everything is ok, but when I changes value of amount field to 1000, script changes value of amount field to default, as if it smaller them minimul-amount.
What I do wrong, and how can I fix this problem?
P.S. Example of this code you can find here - http://friendfi.me/tests/amount.php
You should parse the value before use. Because .val() will return only string type.
$(".amount").on("change", function(){
var am = parseFloat($(".amount").val());
var min = parseFloat($(".minimal-amount").val());
if(am<min){
$(".amount").val($(".minimal-amount").val());
}else{
var am = $(".amount").val();
var oneP = $(".oneprice").val();
var finalPrice = am*oneP;
$(".price").html(finalPrice);
}
});
There are a lot of gotchas in that code. Here is a working JSBin: http://jsbin.com/qilob/2/edit?html,js,output
Highlights
You need the DOM to be initialized before you can work with it.
Wrapping this in a function passed to jQuery will make it wait till
the page finishes loading before manipulating it.
$(function() { ... });
Use cached values since the elements are not going to change much.
This saves the need to parse the selectors multiple times. It also saves
on typing and readability.
var $amount = $("#amount");
var $minimalAmount = $("#minimal-amount");
var $onePrice = $("#oneprice");
var $finalPrice = $("#price");
When parsing a string to an Int you need to use parseInt
var amount = parseInt($amount.val(), 10);
Conversely when parsing a string to a Float you need to use parseFloat
var price = parseFloat($onePrice.val());
JavaScript can not handle float based arithmetic well.
rounding errors are bad especially when dealing with money we need
to move the decimal place to prevent rounding errors in the more significant
parts of the price value.
var total = (amount * (price * 100)) / 100;
See it in action in the JSBin.
I have the following function:
function updateInput(ish){
document.getElementById("BetAmount").value = ish;
}
I have the following HTML inputs:
<input class="defaultText" type="number" name="BetAmount" id="BetAmount" onchange="updateInput(this.value)">
<input type="number" name="PotentialGain" id="PotentialGain" />
When users enter in a bet amount number(BetAmount), I would like to instantly show a calculated PotentialGain, which, for example, can be found by multiplying a constant by the specified bet amount entered in by the user.
I'm not very familiar with JavaScript, so any help is greatly appreciated!
Your code is almost correct - you are showing the result in the BetAmount field so no change is visible.
Change your code to:
document.getElementById("PotentialGain").value = ish;
Here's a working demo. I changed the event to onkeyup as onchange only happens on blur - i.e. when a field loses focus.
Here is the final JQuery function that I used.
function changeBet(bet) {
var moneyline = <?php echo json_encode($win) ?>;
var gain = moneyline * bet;
document.getElementById("PotentialGain").value = gain;
}
Along with these inputs:
<input type="text" name="BetAmount[]" id="BetAmount" onkeyup="changeBet(this.value);" >
<input type="number" name="PotentialGain" id="PotentialGain" />