I am trying do some calculations that take user input and supply the calculated value for the user to see. The user will supply two values and then the result, ADF, will be returned.
Two problems that I am having: The value is calculated before I have entered the second value (FG); and when either value is changed, the old ADF is not replaced. I understand that is because it keeps applying .append(), but I do not know what I need to use instead. I have provided pictures of what is happening. I have listed my code below.
*Note the round() and ADF() functions are my Javascript functions used for the calculations and I didn't think it relevant to list that code. Let me know if you think it is relevant to see it.
Thanks in advance for your help.
function main() {
$(document).on('change', '#Gravities', function () {
OG = $('input[name=OG]').val();
FG = $('input[name=FG]').val();
var calc = round(ADF(OG,FG)*100, 2);
$('.ADFbox').append('<div class="ADF">'+calc+'%</div>');
});
}
$(document).ready(main);
<body>
<form id="Gravities">
<div>
<p><label class="originalGravity">OG: <input type='text' name='OG' value =""></input></label></p>
</div>
<div>
<p><label class="finalGravity">FG: <input type='text' name='FG' value=""></input></label></p>
</div>
</form>
<div class = 'ADFbox'>
<p>ADF:</p>
</div>
</body>
</html>
enter image description here
enter image description here
$(document).on("input", ".gravity", function() {
var thisval = $(this).val()
var nothisval = $(".gravity").not(this).val()
if (thisval.length > 0 && nothisval.length > 0) {//check if one value is empty
OG = $('input[name=OG]').val();
FG = $('input[name=FG]').val();
//var calc = round(ADF(OG, FG) * 100, 2);
var calc = OG * FG;//change this computation
//$('.ADFbox').append('<div class="ADF">' + calc + '%</div>');
$('.ADFbox').text("ADF:" + calc).change();
} else {
$('.ADFbox').text("ADF: 0");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<form id="Gravities">
<div>
<p><label class="originalGravity">OG: <input type='text' class="gravity"name='OG' value ="" /></label></p>
</div>
<div>
<p><label class="finalGravity">FG: <input type='text' class="gravity" name='FG' value=""/></label></p>
</div>
</form>
<div class='ADFbox'>
<p>ADF:</p>
</div>
</body>
Check of each value then proceed if both value has length more than 0
Note: input has no ending tag just close like <input />
To solve this you could place the .adf div in the HTML on load and then simply update it's text() instead of using append() to create a new copy after each calculation.
Below is a working example. Note that I simplified the calculation as you didn't provide the logic of the round() or ADF() functions. Try this:
function main() {
$(document).on('change', '#Gravities', function() {
OG = $('input[name=OG]').val();
FG = $('input[name=FG]').val();
//var calc = round(ADF(OG, FG) * 100, 2);
var calc = OG * FG;
$('.ADFbox .adf').text(calc + '%');
});
}
$(document).ready(main);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="Gravities">
<div>
<p>
<label class="originalGravity">
OG:
<input type='text' name='OG' value="">
</label>
</p>
</div>
<div>
<p>
<label class="finalGravity">
FG:
<input type='text' name='FG' value="">
</label>
</p>
</div>
</form>
<div class='ADFbox'>
<p>ADF: <div class="adf"></div></p>
</div>
The problem you are appending html not updating the existing text value.
Just change your code like below:
$(document).on('change', '#Gravities', function () {
OG = $('input[name=OG]').val();
FG = $('input[name=FG]').val();
if(OG != "" && FG != ""){
var calc = round(ADF(OG,FG)*100, 2);
$('.ADFbox').find("p").html("ADF:"+ calc + '%');
}
});
function main() {
$(document).on('change', '#Gravities', function () {
if($('input[name=OG]').val()!='' && $('input[name=FG]').val()!=''){
var calc = round(ADF(OG,FG)*100, 2);
$('.ADFbox').html('<div class="ADF">'+calc+'%</div>');
}
});
}
$(document).ready(main);
<body>
<form id="Gravities">
<div>
<p><label class="originalGravity">OG: <input type='text' name='OG' value =""></input></label></p>
</div>
<div>
<p><label class="finalGravity">FG: <input type='text' name='FG' value=""></input></label></p>
</div>
</form>
<div class = 'ADFbox'>
<p>ADF:</p>
</div>
</body>
</html>
You have added on change event. that's why it's getting calculated each time when any one of the fields got updated. I made few changes:
<form id="Gravities">
<div>
<p><label class="originalGravity">OG: <input type='number' name='OG' value =""></input></label></p>
</div>
<div>
<p><label class="finalGravity">FG: <input type='number' name='FG' value=""></input>
</label></p>
</div>
<button type="button" id="fgs">
Find ADF</button>
</button>
</form>
<div class = 'ADFbox'>
<p>ADF:</p>
</div>
function main() {
$("#fgs").on('click', function () {
OG = $('input[name=OG]').val();
FG = $('input[name=FG]').val();
var calc = OG*FG;
document.getElementsByClassName("ADFbox")[0].innerHTML= "ADF:"+" " +calc;
});
}
$(document).ready(main);
created working fiddle for you: https://jsfiddle.net/Safoora/hspdgqca/15/
Sorry if I'm not understanding you. As per my understanding you need to calculate only if both inputs field are changed? If it is so, you can do like this:
function main() {
$(document).on('change', '#Gravities input', function () {
OG = $('input[name=OG]');
FG = $('input[name=FG]');
$(this).data('changed',true); // set "changed=true" for current input
// Check if both input fields are changed
if(OG.data('changed') == true && FG.data('changed') == true){
//var calc = round(ADF(OG.val(),FG.val())*100, 2); // uncomment this
var calc = OG.val() * FG.val(); // comment this
$('.ADFbox').html(function(){
$('#Gravities input').data('changed',false); // set "changed=false" for next query
return '<div class="ADF">'+calc+'%</div>'
});
}
});
}
$(document).ready(main);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="Gravities">
<div>
<p><label class="originalGravity">OG: <input type='text' name='OG' value =""></input></label></p>
</div>
<div>
<p><label class="finalGravity">FG: <input type='text' name='FG' value=""></input></label></p>
</div>
</form>
<div class = 'ADFbox'>
<p>ADF:</p>
</div>
Related
I have a button that creates 4 input elements inside a DIV after click:
<div id="content"></div>
<button class="check">Check</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
var num = 4;
$(".check").click(function(){
for(i=0; i<num;i++){
$("#content").append("<input id='input"+i+"' type='text'><br>");
}
});
</script>
But the problem is I want input id number continues the enumeration (like this example) instead of return to zero:
<div id="content">
<input id="input0" type="text">
<input id="input1" type="text">
<input id="input2" type="text">
<input id="input3" type="text">
<input id="input4" type="text">
<input id="input5" type="text">
<input id="input6" type="text">
<input id="input7" type="text">
...and continues
</div>
How can I fix it?
You can check the id of the last input. Here I am calculating start and end of for loop based on the total number of elements in #container.
var num = 4;
$(".check").click(function() {
var start = $("#content input").length;
var end = start + num;
for (i = start; i < end; i++) {
var id = 'input' + i;
$("#content").append("<input id='"+id+"' type='text' value='"+id+"'><br>");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content"></div>
<button class="check">Check</button>
PS: Here input value is just to demonstrate the id setting to input.
You need some kind of global variable here, or use that simple one:
var getID = (function () {
var id = 0;
return function () { return ++id; }
})();
So whenever you call getID() the »internal« id will be incremented, so each call will yield an new ID.
$(".check").click(function() {
for(var i = 0; i < 4; i++) {
$('<input type="text">') //create a new input
.attr('id', 'input' + $('#content input').length) //id based on number of inputs
.appendTo('#content'); //append it to the container
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content"></div>
<button class="check">Check</button>
If you're asking how to have a stack of elements to begin with, and then continue enumeration from there, you simply need to set a variable to the ID of the latest element.
All you need to do is count the number of elements. This can be done with a combination of .querySelectorAll() and .length.
Then simply have your loop start at this new value instead of 0.
This can be seen in the following:
var total_desired = 20;
var start = document.querySelectorAll('#content > input').length;
console.log(start + " elements to start with");
$(".check").click(function() {
for (i = start; i < total_desired; i++) {
$("#content").append("<input id='input" + i + "' type='text'><br>");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="check">Check</button>
<div id="content">
<input id="input0" type="text">
<input id="input1" type="text">
<input id="input2" type="text">
<input id="input3" type="text">
<input id="input4" type="text">
<input id="input5" type="text">
<input id="input6" type="text">
<input id="input7" type="text"> ...and continues
</div>
Having said that, it's unlikely that you actually need simultaneous ID <input> elements, and you may benefit from classes instead.
You can create this object:
var MyId = {
a: 0,
toString() {
return this.a++;
}
}
And concatenate it into the string. Automatically will increase the counter.
<div id="content"></div>
<button class="check">Check</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
var GetID = {
a: 0,
toString() {
return this.a++;
}
}
var num = 4;
$(".check").click(function(){
for(i=0; i<num;i++){
$("#content").append("<input id='input"+GetID+"' type='text'><br>");
}
});
</script>
I would like to create similar calculator like here. It calculates the volume of a mulch. Visitor inserts three numbers: width, length and height (thickness) and it tells how much it has to buy.
html:
<form method="post" accept-charset="UTF-8">
<div class="form_area">
<div class="form_fields">
<div class="form_field ">
<label class="form_field_label">Width (m)</label>
<input type="text" value="" name="laius" id="laius" rel="calc" class="form_field_textfield form_field_size_medium">
</div>
<div class="form_field ">
<label class="form_field_label">Length (m)</label>
<input type="text" value="" name="pikkus" id="pikkus" rel="calc" class="form_field_textfield form_field_size_medium">
</div>
<div class="form_field ">
<label class="form_field_label">Thickness (cm)</label>
<input type="text" value="" name="paksus" id="paksus" rel="calc" class="form_field_textfield form_field_size_medium">
</div>
<div class="form_field ">
<label class="form_field_label">Total (m<sup>3</sup>)</label>
<input type="text" value="" readonly name="kokku" id="kokku" class="form_field_textfield form_field_size_small">
</div>
</div>
<div class="form_submit">
<input type="submit" value="Arvuta" id="calc_submit" name="commit">
</div>
</div>
</form>
javascript:
! function($) {
$(function() {
$("[rel='calc']").arvutus();
});
$.fn.arvutus = function() {
var inputs = $(this);
var kokku = $("#kokku:first");
inputs.bind("change keyup", function() {
var obj = $(this);
if (obj.val() !== "") {
parseFloat(obj.val()).toFixed(2);
};
arvuta();
});
$("#calc_submit").bind("click", function(e) {
e.preventDefault();
arvuta();
});
function arvuta() {
var width = inputs.filter("#laius").val();
width = width.toString();
width = width.replace(",", ".");
var lenght = inputs.filter("#pikkus").val();
lenght = lenght.toString();
lenght = lenght.replace(",", ".");
var thickness = inputs.filter("#paksus").val();
thickness = thickness.toString();
thickness = thickness.replace(",", ".");
thickness = thickness / 100;
var sum = width * lenght * thickness
sum = sum.toFixed(2);
kokku.val(sum + " m3 multši.");
};
};
}(window.jQuery);
I inserted html and javascript into jsfiddle, but mine doesn't work. Probably i miss something very obvious. some more javascript?
update: a little while ago, somebody provided a working code, but moderator removed it so quickly i couldn't copy it... :(
The code parseFloat(obj.val()).toFixed(2) returns a value, but you're not doing anything with it. Should it be stored somewhere so you can use it in calculating the volume?
<!DOCTYPE html>
<html>
<body>
<form>
Birth Year:<br>
<input type="number" name="birthYear">
<br>
Current Year:<br>
<input type="number" name="currentYear">
</form>
<button onclick="calculateAge()">Calculate Age</button>
<div id="output"></div>
<script>
function calculateAge(ghF, xhF) {
var ghF = "birthYear"
var xhF = "currentYear"
return (xhF - ghF);
} {
document.getElementByID("output").innerHTML = text;
};
</script>
</body>
When I click on the button it should print out "You are x age". Where would I add that text? At the moment nothing happens when I click on the button.
getElementById will return the DOM element having id as mentioned argument. .value is property of input element which will give the value of input
Instead of returning value, you must set the innerHTML/innerText after doing subtraction.
Note: You must assign unique id attributes to the element to retrieve DOM element.
function calculateAge() {
var ghF = document.getElementById("birthYear").value;
var xhF = document.getElementById("currentYear").value;
document.getElementById("output").innerHTML = xhF - ghF;
}
<form>
Birth Year:
<br>
<input type="number" name="birthYear" id="birthYear">
<br>Current Year:
<br>
<input type="number" name="currentYear" id="currentYear">
</form>
<button onclick="calculateAge()">Calculate Age</button>
<div id="output"></div>
function calculateAge() {
var ghF = document.getElementById("birthYear").value;
var xhF = document.getElementById("currentYear").value;
document.getElementById("output").innerHTML="You are " +(xhF - ghF) + " age";
}
EXAMPLE
The function is badly formed.
This will do the trick:
function calculateAge() {
var ghF = document.querySelector('[name="birthYear"]').value;
var xhF = document.querySelector('[name="currentYear"]').value;
document.getElementById("output").innerHTML = "You are "+(xhF - ghF)+" age";
}
<form>
Birth Year:
<br>
<input type="number" name="birthYear">
<br>
Current Year:
<br>
<input type="number" name="currentYear">
</form>
<button onclick="calculateAge()">Calculate Age</button>
<div id="output"></div>
I have a user enter biograpgy in a text box html for that is
<p>Biography:
<input type="text" id="biography" name="biography" />
<span id="biographyInvalid" style="color:red; visibility:hidden"> Biography is Invalid </span>
</p>
for Javascript i have a checkme function that is called and i want to do a check inside of it
function checkme(){
var biography=document.getElementById('biography').value;
}
how can i count number of words, do i first convert it to string and then separate with spaces
<div>
<div id="count">145</div>
<div id="barbox"><div id="bar"></div></div>
</div>
<textarea id="contentbox"></textarea>
and js
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#contentbox").keyup(function()
{
var box=$(this).val();
var main = box.length *100;
var value= (main / 145);
var count= 145 - box.length;
if(box.length <= 145)
{
$('#count').html(count);
$('#bar').animate(
{
"width": value+'%',
}, 1);
}
else
{
alert(' Full ');
}
return false;
});
});
</script>
$('#contentbox').keyup(function(){} - contentbox is the ID of the textbox.
Using $(this).val() getting the textbox value.
bar is the div ID of the count meter $('#bar').animate() increasing the width.
js:
$('#biography').keyup(function () {
var words = this.value.match(/\S+/g).length;
$('#count').html('Words Count:'+words);
});
HTML:
<div id="count"></div>
This gives you correct words count
This is working example
the HTML
<form name="myform" method="post" action="">
<textarea name="inpString" cols="80" rows="4" onkeyup="countNoOfWords()" >This is a sample text that has been typed to count the number of words it contains. Click the button below to find out.</textarea>
<br />
<input name="noofwords" type="text" value="" size="6" />
</form>
The JS function
<script type="text/javascript">
function countNoOfWords(){
document.myform.noofwords.value = document.myform.post_content.value.split(' ').length;
}
</script>
reference
$('input').keyup(function() {
var cs = this.value.match(/\S+/g).length;
$('#biography').text(cs);
});
Demo - http://jsfiddle.net/hNn5b/685/
<script>
var monster = 40
var damage = Math.floor(Math.random()*10)
</script>
<p>Type 'Spark' or 'Fire' to Attack.</p>
<form action="javascript:alert( 'Enemy has' + (monster- damage) + 'Health!' );"
>
<div>
<input type="text">
<input type="submit">
</div>
</form>
<span></span>
</body>
So this is my code so far I type anything in it gives me a text box saying the Enemy has whatever health, I would like to have it where only if you type spark or fire into the input field you get that text box and if you type something random like skdfslkfha nothing happens (unlike now :/)
JS Fiddle
html
<form action="javascript:ale()">
<div>
<input type="text" id="find">
<input type="submit">
</div>
</form>
javascript
function ale() {
a = document.getElementById("find").value
if (a == 'Spark' || a == 'Fire') {
var monster = 40
var damage = Math.floor(Math.random() * 10)
alert('Enemy has ' + (monster - damage) + ' Health!');
}
else{
alert('worng keyword');
}
}