I want every time when user enter number ,print the new one + old one in console
here is html script
<input type="number"value=""/>
<button>click</button>
my jquery code
$("button").click(function (){
var x = $("input").val();
x+=x;
console.log(x);
});
You have to initialize the value outside somewhere to keep its state.
html
<input type="number" id="inp" value=""/>
<button>click</button>
js
var x = 0;
$("button").click(function (){
var y = parseInt($("#inp").val());
x+=y;
console.log(x);
});
hope this will help to you. refer the working demo.
var thevalue = 0;
$("#click").click(function(){
$("#display").text("The Value is :");
var theinput_value = parseInt($("#num").val());
thevalue += theinput_value;
$("#display").append(thevalue);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Enter the nubmer : <input type="number" id="num"><button id="click">Click on me !</button>
<br>
<p id="display">The Value is :</p>
You just need to make sure x is a global variable so you can save it's value and used each time the click handler is triggered.
I added input casting to avoid string concatenation when using the addition assignment operator.
var x = 0;
$("button").click(function (){
// Get the input
var current_input = parseInt($("input").val());
// If input is not a number set it to 0
if (isNaN(current_input)) current_input = 0;
// Add the input to x
x+=current_input;
// Display it
console.log(x);
});
Related
I got a input number into a var. I subtracted it to a number.
Thank you vicodin for helping me! I fixed it and it works! (I changed names for my program)
<!DOCTYPE html>
<html>
<body>
<p></p>
<span><input type="number" id="guess1"><p id="g1s"></p></span>
<input type="button" onclick="Calculate()" value="Calculate">
<script>
function Calculate() {
var GuessCon1 = document.getElementById("guess1").value;
var GuessCon1sub = GuessCon1 - 500;
document.getElementById("g1s").innerHTML = GuessCon1sub;
}
</script>
</body>
</html>
You assigned a string "numb1" to variable g. If you want to get the value of the input, you need to find that element (e.g. with document.geElementById method) and take a value from it.
Also, you want to trigger calculation, for example by a button click. I added a code in a snippet, you can run it and play around with it to get the idea.
var button = document.getElementById("substract")
button.onclick = function() {
var g = document.getElementById("numb1").value
var a = 578;
var x = g - a;
document.getElementById("demo").innerHTML = x;
}
<input type="number" id="numb1">
<input type="submit" id="substract">
<p id="demo"></p>
Related links:
Input Text value Property
onclick event
Trying to pass changes in input field to a variable simultaneously with the change. But for some reason, my code detects only first change. For example, if I enter "100" into the field, it only detects "1". Nothing happens afterwards.
Here is my jquery
$(document).ready(function() {
var wholeshort = $(".shorcodeval").val();
a = wholeshort;
var w = /width="(.*?)"/.exec(a)[1];
$(".widthinput").on('input', function() {
nw = $(this).val();
wholeshort = wholeshort.replace(w, nw);
$(".shorcodeval").val(wholeshort);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="widthinput" />
<textarea class="shorcodeval">[example width="300px"]</textarea>
here is the fiddle
https://jsfiddle.net/3a6n1fux/
The problem is that after the first input you save [example width="1"] in wholeshort, but w is 300px so you try to replace 300px in [example width="1"].
To solve that you would need to save the result of wholeshort.replace(w, nw) in an own variable or pass it directly to .val(wholeshort.replace(w, nw)).
$(document).ready(function() {
var wholeshort = $(".shorcodeval").val();
var w = /width="(.*?)"/.exec(a)[1];
$(".widthinput").on('input', function() {
var nw = $(this).val();
$(".shorcodeval").val(wholeshort.replace(w, nw));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="widthinput" />
<textarea class="shorcodeval">[example width="300px"]</textarea>
I have numeric values with many decimal places and the precision is required for other functions. I want to present the values in a form, so the user can change the values if necessary.
To increase the readability, I want to display the values rounded to 2 decimal places, but if the user clicks on an input field, the complete value should be presented. By doing this, the user can see the real value and adjust them better.
Example:
HTML
<button id="myBtn" onclick="fillForm()">Try it</button>
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" onchange="myFunction()" >
</fieldset>
</form>
JavasSript
<script>
//Example values that should be presented
var x = 3.14159265359;
function fillForm(){
document.getElementbyId("myInput1").value = x;
}
function myFunction(){
x = document.getElementbyId("myInput1");
}
</script>
The form input value should be " 3.14 " and if the user clicks in the field, the displayed value should be 3.14159265359.
Now the user can change the value and the new value has to be saved.
Because this is for a local 1 page website with no guaranty of internet connection, it would be an asset but not a requirement, to do it without an external script (jquery …).
you can use focus and blur event to mask/unmask you float, then simply store the original value in a data param, so you can use the same function to all input in your form ;)
function fillForm(inputId, val)
{
var element = document.querySelector('#'+inputId);
element.value = val;
mask(element);
}
function mask(element) {
element.setAttribute('data-unmasked',element.value);
element.value = parseFloat(element.value).toFixed(2);
}
function unmask(element) {
element.value = element.getAttribute('data-unmasked') || '';
}
<button onclick="fillForm('myInput1',3.156788)">Fill!</button>
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" onblur="mask(this)" onfocus="unmask(this)" >
</fieldset>
</form>
Edit: added "fillForm()" :)
Just use .toFixed(). It accepts one argument, an integer, and will display that many decimal points. Since Javascript primitives are immutable, your x variable will remain the same value. (also when getting/setting the value of an input use the .value property
function fillForm(){
document.getElementbyId("myInput1").value = x.toFixed(2);
}
If you need to save it you can store it in a new value
var displayX = x.toFixed(2)
Here is my solution. I hope you have other suggestions.
HTML
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" >
</fieldset>
</form>
<button id="myBtn" onclick="fill_form()">fill form</button>
JavasSript
<script>
var apple_pi = 10.574148541;
var id_form = document.getElementById("myForm");
//Event listener for form
id _form.addEventListener("focus", copy_input_placeh_to_val, true);
id _form.addEventListener("blur", round_input_2decimal, true);
id _form.addEventListener("change", copy_input_val_to_placeh, true);
// Replace input value with input placeholder value
function copy_input_placeh_to_val(event) {
event.target.value = event.target.placeholder;
}
// Rounds calling elemet value to 2 decimal places
function round_input_2decimal(event) {
var val = event.target.value
event.target.value = Number(val).toFixed(2);
}
// Replace input placeholder value with input value
function copy_input_val_to_placeh(event) {
event.target.placeholder = event.target.value;
}
// Fills input elements with value and placeholder value.
// While call of function input_id_str has to be a string ->
//fill_input_val_placeh("id", value) ;
function fill_input_val_placeh (input_id_str, val) {
var element_id = document.getElementById(input_id_str);
element_id.placeholder = val;
element_id.value = val.toFixed(2);
}
// Writes a value to a form input
function fill_form(){
fill_input_val_placeh("myInput1", apple_pi);
}
</script>
Here is an running example
https://www.w3schools.com/code/tryit.asp?filename=FLDAGSRT113G
Here is solution, I used focus and blur listeners without using jQuery.
I added an attribute to input named realData
document.getElementById("myInput1").addEventListener("focus", function() {
var realData = document.getElementById("myInput1").getAttribute("realData");
document.getElementById("myInput1").value = realData;
});
document.getElementById("myInput1").addEventListener("blur", function() {
var realData = Number(document.getElementById("myInput1").getAttribute("realData"));
document.getElementById("myInput1").value = realData.toFixed(2);
});
function fillForm(value) {
document.getElementById("myInput1").value = value.toFixed(2);
document.getElementById("myInput1").setAttribute("realData", value);
}
var x = 3.14159265359;
fillForm(x);
<button id="myBtn" onclick="fillForm()">Try it</button>
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" realData="" onchange="myFunction()" >
</fieldset>
</form>
jsfiddle : https://jsfiddle.net/mns0gp6L/1/
Actually there are some problems that needs to be fixed in your code:
You are redeclaring the x variable inside your myFunction function with var x =..., you just need to refer the already declared x without the var keyword.
Instead of using document.getElementById() in myFunction, pass this as a param in onchange="myFunction(this)" and get its value in the function.
Use parseFloat() to parse the value of your input to a float, and use .toFixed(2) to display it as 3.14.
This is the working code:
var x = 3.14159265359;
function fillForm() {
document.getElementById("myInput1").value = x.toFixed(2);
}
function myFunction(input) {
x = parseFloat(input.value);
}
To display the original number when you click on the input you need to use the onfocus event, take a look at the Demo.
Demo:
var x = 3.14159265359;
function fillForm() {
document.getElementById("myInput1").value = x.toFixed(2);
}
function focusIt(input){
input.value = x;
}
function myFunction(input) {
x = parseFloat(input.value);
}
<button id="myBtn" onclick="fillForm()">Try it</button>
<form id="myForm">
<fieldset>
<input type="text" id="myInput1" onchange="myFunction(this)" onfocus="focusIt(this)">
</fieldset>
</form>
Hi I am NewBee in Javascript. This is my second week.
Below is the code that has a form with three input fields.
The relationship of the fields is:
the second field is twice the value of the first field
the third field is the square of the first field
I have managed to do the above but i am not able to do the below :
If a user enters a value in the second or third field, the script should calculate the appropriate value in the other fields. Currently the code works well ONLY if I enter the value in the first field.
I hope I explained well in other words : how do I enter say 144 in the last textbox and the other 2 textboxes show 12 and 24 respectively. Or If I enter 24 first and first and the third text boxes show 12 and 144.
Thanks
Vipul
<html>
<head>
<script>
window.onload = init;
function init() {
var button = document.getElementById("usrButton");
button.onclick = save;
onkeyup = doMath;
function doMath(){
var base = document.getElementById("base").value;
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value = (base*2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
}
</script>
</head>
<body>
<form>
<input type="text" name="base" id="base" onkeyup= "doMath()">
<br><br>
<input type="text" name="baseNumber_timesTwo" id="baseNumber_timesTwo" onkeyup= doMath()>
<br><br>
<input type="text" name="baseNumber_square" id="baseNumber_square" onkeyup= doMath()> <br><br>
</form>
</body>
</html>
take a look at the code below:
<html>
<head>
<script>
window.onload = init;
var init = function(){
var button = document.getElementById("usrButton");
button.onclick = save;
onkeyup = doMath;
}
var doMathbase = function(){
console.log('here');
var base = document.getElementById("base").value;
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value = (base*2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
var doMathBase2Time = function(){
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value;
var base = document.getElementById("base").value = (baseNumber_timesTwo/2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
</script>
</head>
<body>
<form>
<input type="text" name="base" id="base" onkeyup= "doMathbase()">
<br><br>
<input type="text" name="baseNumber_timesTwo" id="baseNumber_timesTwo" onkeyup= "doMathBase2Time()">
<br><br>
<input type="text" name="baseNumber_square" id="baseNumber_square" onkeyup= "doMathBaseSquare()">
<br><br>
</form>
</body>
You need to bind another function to the second and third field. I did it to the second. Now if you entered a number in the second field it return the 'base' number and the square of the base.
Try do it for the third :)
This should fit your needs:
Fiddle
//declaring those earlier saves you to get those by ID every
//time you call "doMath()" or something else
var base = document.getElementById("base");
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo");
var baseNumber_square = document.getElementById("baseNumber_square");
function clearUp() {
base.value = "";
baseNumber_timesTwo.value = "";
baseNumber_square.value = "";
}
function doMath() {
//check which of the fields was filled
if(baseNumber_timesTwo.value){
base.value = baseNumber_timesTwo.value / 2;
}
if(baseNumber_square.value){
base.value = Math.sqrt(baseNumber_square.value);
}
//fill other fields according to that
baseNumber_timesTwo.value = (base.value*2);
baseNumber_square.value = (base.value*base.value) ;
}
As you see: There is no need to write more than one arithmetic function if you make sure that only one value is given at the time of evaluation (this is achieved by the cleanUp()
method)
However there are still some flaws in this solution! Since you are a js beginner I would suggest you to read the code and think about possible solutions for those problems as a little exercise :-)
- You cannot enter a 2 (or more) digit number in any field, why not? What do you have to change in order to allow such numbers as input?
- Why is it better (in this case!) to set the values to " " instead of '0' in the cleanUp function? Why does the code break when you try using '0' instead of "" ?
- Why does doMath() only check for values in the last two field (baseNumber_timesTwo and baseNumber_square) while ignoring the 'base' field?
Greetings, Tim
I am trying to pass on JQuery values to hidden textboxes (to send as a form later) as well as divs t
hat displays on the front end. I also want to tally these items as the value is passed to them. I have Frankensteined this bit of code which passes on the value to the the input boxes and the divs and it also tallies them onclick. I am just struggling to get the sum to display in #total_div. Can anyone point me in the right direction please?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$('#my_div').click(function() {
$('#my_value_1').val("100");
$('#my_value_1_div').html( "100" );
$('#my_div').click(addNumbers('total'));
});
});
$(document).ready(function(){
$('#my_div_2').click(function() {
$('#my_value_2').val("200");
$('#my_value_2_div').html( "200" );
$('#my_div_2').click(addNumbers('total'));
});
});
function addNumbers()
{
var val1 = parseInt(document.getElementById("my_value_1").value);
var val2 = parseInt(document.getElementById("my_value_2").value);
var ansD = document.getElementById("total");
ansD.value = val1 + val2;
}
</script>
<h2>My pretty front end</h2>
<div id="my_div">ADD THIS VALUE 1</div>
<div id="my_div_2">ADD THIS VALUE 2</div>
VALUE 1: <div id="my_value_1_div">VALUE 1 GOES HERE</div>
VALUE 2: <div id="my_value_2_div">VALUE 2 GOES HERE</div>
TOTAL: <div id="total_div">SUM MUST GO HERE</div>
<h2>My hidden Form</h2>
Value 1: <input type="text" id="my_value_1" name="my_value_1" value="0"/>
Value 2: <input type="text" id="my_value_2" name="my_value_2" value="0"/>
<input type="button" name="Sumbit" value="Click here" onclick="javascript:addNumbers()"/>
Total: <input type="text" id="total" name="total" value=""/>
EDIT
Ok so thanks to the advice I got the above working but now I need to clear the amounts. This is what I have done, it is almost there I think but I'm getting the incorrect sum.
$('#clear').click(function() {
$('#my_value_1').val('0');
$('#my_value_1_div').html( "0" );
$('#clear').click(minusNumbers('total'));
});
function minusNumbers()
{
var minval1 = parseInt(document.getElementById("my_value_1").value);
var minval2 = parseInt(document.getElementById("total").value);
var minansD = document.getElementById("total");
minansD.value = minval2 - minval1;
$('#total_div').text(minansD.value);
}
Update #total_div text in addNumber function as,
function addNumbers()
{
var val1 = parseInt(document.getElementById("my_value_1").value);
var val2 = parseInt(document.getElementById("my_value_2").value);
var ansD = document.getElementById("total");
ansD.value = val1 + val2;
$('#total_div').text(ansD.value);
}
Demo
replace:
function addNumbers()
{
var val1 = parseInt(document.getElementById("my_value_1").value);
var val2 = parseInt(document.getElementById("my_value_2").value);
var ansD = document.getElementById("total");
ansD.value = val1 + val2;
}
with:
function addNumbers()
{
var val1 = parseInt(document.getElementById("my_value_1").value);
var val2 = parseInt(document.getElementById("my_value_2").value);
var ansD = document.getElementById("total");
ansD = val1 + val2;
$('#total').val(ansD);
}
click(addNumbers('total')); first calls addNumbers with an unused parameter 'total' then gets the return value of addNumbers (null or undefined) and sets that as the click() handler for the next click.
I think you probably meant
$('#my_div').click(addNumbers);
that means, "run the addNumbers function, defined below, next time I click my_div".
or just
addNumbers();
that means, "run the addNumbers function now" (at the first click)
Note though that when you click and call addNumbers, one of the numbers may not yet be copied, so you would be adding 100+"" or ""+200 so you really have to think about what you want to do.