Please read the form and javascript carefully. My goal is grab text input value 'a' and 'b' then total integer value will be dynamically set to text input id called- 'x'. How can i set dynamic javascript value to html text input? Also it should be real time updating so user can see the total value of a+b on x. x is actually displaying the value and will be submitting this value if 'submit' button pressed.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js" type="text/javascript"></script>
</head>
<body>
<form method="post">
<input type="text" id="a" value="5">
<input type="text" id="b" value="2">
<input type="text" id="x" value="dynamic_value_from_javascript">
<input type="submit" name="submit" value="submit">
</form>
<script type='text/javascript'>
$('#a').keyup(updatetxt);
$('#a').keydown(updatetxt);
var a = $('#a');
var b = $('#b');
var x = a+b;
function updatetxt() {
$('#x').val($(x).val());
}
</script>
</body>
</html>
Check this fiddle I have made recently,It will update real time. let me know if any query occurs
$(function() {
$( "#a" ).keyup(function() {
var a = $('#a').val();
var b = $('#b').val();
var c = parseInt(a) + parseInt(b);
$('#c').val(c);
});
$( "#b" ).keyup(function() {
var a = $('#a').val();
var b = $('#b').val();
var c = parseInt(a) + parseInt(b);
$('#c').val(c);
});
});
<input type="text" id="a" value="1"/><br>
<input type="text" id="b" value="2"/><br>
<input type="text" id="c" value=""/><br><br>
My Jsfiddle link
There are a few problems with your code, I have fixed them below:
You need to get values of a and b during the keyup events.
You need subscribe to keyup events of both a and b inputs.
In order to add integer values, you can use parseInt
Call updatetxt for the first time without any events, so that it can set the total value based on default values in the inputs
$('#a').keyup(updatetxt);
$('#b').keyup(updatetxt);
function updatetxt() {
var a = $('#a').val();
var b = $('#b').val();
var x = parseInt(a) + parseInt(b);
$('#x').val(x);
}
updatetxt();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="a" value="5">
<input type="text" id="b" value="2">
<input type="text" id="x" value="">
Related
I'm trying to create a form based calculator for a business equation which works out break-even return on ad spend.
The fucntion works, I've testred it through the console on Chrome. But this is ony when I set the variables to numbers, I'm struggling to use the data from the form to work it out.
I don't know if using a form is right for this. The part I can't figure out is linking the HTML form data to the JS variables.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title></title>
</head>
<body>
<form id="main">
<label for="rprice">Retail Price: </label>
<input type="number" id="rprice"><br><br>
<label for="cogoods">Cost of Goods: </label>
<input type="number" id="cogoods"><br><br>
</form>
</body>
</html>
let retailPrice = document.getElementById("rprice")
let costOfGoods = document.getElementById("cogoods")
let difference = retailPrice - costOfGoods
function calculate () {
return (retailPrice / difference)
};
Take in consideration:
to get the value of any input use attribute .value
function calculate (){
let difference = retailPrice.value - costOfGoods.value
return retailPrice.value / difference
};
Add submit input to fire the function calculate()
<input type="submit" value="calculate">
to get the returned value from a function you have to call it.
let form = document.getElementById("main");
form.addEventListener("submit",function(event){
event.preventDefault();
console.log(calculate());
});
Note: event.preventDefault() prevent the form from reloading.
let retailPrice = document.getElementById("rprice");
let costOfGoods = document.getElementById("cogoods");
let form = document.getElementById("main");
form.addEventListener("submit",function(event){
event.preventDefault();
console.log(calculate());
document.getElementById("display").innerHTML = calculate();
});
function calculate (){
let difference = retailPrice.value - costOfGoods.value
return retailPrice.value / difference
};
<form id="main">
<label for="rprice">Retail Price: </label>
<input type="number" id="rprice" ><br><br>
<label for="cogoods">Cost of Goods: </label>
<input type="number" id="cogoods" ><br><br>
<input type="submit" value="calculate">
</form>
<div id="display"></div>
I am developing an app in Django. In my forms it is possible to have dependent fields. I would like to use this plugin. However, field dependencies may vary depending on the user's choices.
The fields in my forms look more or less like this:
<input type="text" name="name1" data-dependency="id_name2" class="textinput textInput form-control" id="id_name1">
The data-dependency attribute indicates which fields this field depends on. So in this case the name1 field will somehow depend on the name2 field.
I wrote this sample script to dynamically add dependencies:
$('document').ready(function(){
var name = document.getElementById("id_name1");
var data_dependency = name.getAttribute('data-dependency');
var dependencies = data_dependency.split(";")
var i =0;
for(i=0; i<dependencies.length; i++){
var d = dependencies[i];
var elem = document.getElementById(d);
$(name).dependsOn({
'#id_name2' : {
values: ['yes']
}
});
}
});
At this point, I have a fixed id #id_name2 on which depends field name1 . Is there any way to pass on any element taken from the dependencies?
A simple working example (you only need to download two scripts):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="dependsOn.min.js"></script>
<script>
$('document').ready(function(){
var element = document.getElementById("myText2");
var data_dependency = element.getAttribute('data-dependency');
var dependencies = data_dependency.split(";")
var i =0;
for(i=0; i<dependencies.length; i++){
var d = dependencies[i];
var tmp = document.getElementById(d);
$(element).dependsOn({
'#myText1' : {
values: ['yes']
}
});
}
});
</script>
</head>
<body>
<form id="myForm">
<label for="myText1">Type yes</label>
<input type="type" id="myText1">
<label for="myText2">Input</label>
<input type="text" id="myText2" value="" data-dependency="myText1">
</form>
</body>
</html>
The key to solving the problem was to know that dependsOn accepts the dictionary as an argument.
It is enough to create a suitable dictionary and pass it on as an argument.
So the solution is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="dependsOn.min.js"></script>
<script>
function get_id(element) {
return '#' + element.id;
};
$('document').ready(function(){
var element = document.getElementById("myText2");
var data_dependency = element.getAttribute('data-dependency');
var dependencies = data_dependency.split(";")
var i =0;
for(i=0; i<dependencies.length; i++){
var d = dependencies[i];
var tmp = document.getElementById(d);
var data = {}
data[get_id(tmp)] = {values: ['yes'] }
$(element).dependsOn(data);
}
});
</script>
</head>
<body>
<form id="myForm">
<label for="myText1">Type yes</label>
<input type="type" id="myText1">
<label for="myText2">Input</label>
<input type="text" id="myText2" value="" data-dependency="myText1">
</form>
</body>
I need to do a simple homework where you enter two integers in two text fields of a form and then you compute the sum and you print it in a "text field (not editable)". My program seems to work but it prints the right output and immediately reload the page. I want the page to remain with the printed output if the user does not click again on "submit" button
Here is my code HTML & JS :
function updateExpr() {
var x1 = document.getElementById("n1").value;
var x2 = document.getElementById("n2").value;
var sum = +x1 + +x2;
document.getElementById("sum").innerHTML = +x1 + +x2;
}
<!DOCTYPE html>
<html>
<head>
<title>Number in a form</title>
<link href="mystyle.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="function.js">
</script>
</head>
<body>
<div id="mainDiv">
<H3>Insert two positive numbers</H3>
<form>
First number:<br>
<input id="n1" type="text" name="firstname"><br>
Second number:<br>
<input id="n2" type="text" name="lastname">
<BR>
<input type="submit" value="Submit" onClick="updateExpr()"/><BR><BR>
</form>
The sum is:<br>
<output id="sum" name="x" for="a b"></output>
</div>
<noscript>
Sorry: Your browser does not support or has disabled javascript
</noscript>
</body>
</html>
When form is submited, the page will be reloaded. To prevent this you should change input type attribute from submit to button.
<input type="submit" value="Submit" onClick="updateExpr()"/>
to
<input type="button" value="Submit" onClick="updateExpr()"/>
You can simply avoid server call by changing your form tag
<form onSubmit="return false">
You dont really need a form to do something like this.
Forms send values to the backend, e.g. a server.
You only want to manipulate some front-end elements like a container to have some new text inside it.
a <form> tag typically sends you to some URI with some aprameters,
this is done by the actions attribute.
<form action="addnames.php">
for example would call the addnames.php script on your server...
You dont need a server tho..look below:
function updateExpr() {
var x1 = document.getElementById("n1").value;
var x2 = document.getElementById("n2").value;
var sum =x1 +x2;
document.getElementById("sum").innerHTML = sum;
}
<h2>HTML Forms</h2>
First name:<br>
<input id="n1" type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input id="n2" type="text" name="lastname" value="Mouse">
<br><br>
<button type="submit" onclick="updateExpr()">Submit</button>
<div id="sum">
</div>
<script>
</script>
I would recommand you to add onSubmit method to the form instead of onclick to the input.
Also you better add a return : false to your function and add onsubmit="return updateExpr()".
function updateExpr() {
var x1 = document.getElementById("n1").value;
var x2 = document.getElementById("n2").value;
var sum = +x1 + +x2;
document.getElementById("sum").innerHTML = +x1 + +x2;
return false;
}
<!DOCTYPE html>
<html>
<head>
<title>Number in a form</title>
<link href="mystyle.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="function.js">
</script>
</head>
<body>
<div id="mainDiv">
<H3>Insert two positive numbers</H3>
<form onsubmit="return updateExpr()">
First number:<br>
<input id="n1" type="text" name="firstname"><br>
Second number:<br>
<input id="n2" type="text" name="lastname">
<BR>
<input type="submit" value="Submit" onClick="updateExpr()"/><BR><BR>
</form>
The sum is:<br>
<output id="sum" name="x" for="a b"></output>
</div>
<noscript>
Sorry: Your browser does not support or has disabled javascript
</noscript>
</body>
Another way of doing this would have been to add a button outside of the form linked to the function by onclick event
juste add preventDefault(), like this
function updateExpr(e) {
e.preventDefault();
var x1 = document.getElementById("n1").value;
var x2 = document.getElementById("n2").value;
var sum = +x1 + +x2;
document.getElementById("sum").innerHTML = +x1 + +x2;
}
I have created sum of 2 number but now want to change this code with multipy two numbers.
<html>
<head>
<title>Jquery</title>
<script src="jquery.js"></script>
<script>
$(function(){
$('.ck').click(function(){
var a=parseInt($('.n1').val());
var b=parseInt($('.n2').val());
var c=a+b;
alert("The sum is " + c);
})
})
</script>
</head>
<body>
Enter Number 1<input type="text" class="n1"/><br/>
Enter Number 2<input type="text" class="n2"/><br/>
<input type="button" value="Add" class="ck"/>
</body>
</html>
The way to multiply two numbers in javascript is with the operator *.
Your new code would look like this, replacing + with *:
<html>
<head>
<title>Jquery</title>
<script src="jquery.js"></script>
<script>
$(function(){
$('.ck').click(function(){
var a=parseInt($('.n1').val());
var b=parseInt($('.n2').val());
var c=a * b;
alert("The sum is " + c);
})
})
</script>
</head>
<body>
Enter Number 1<input type="text" class="n1"/><br/>
Enter Number 2<input type="text" class="n2"/><br/>
<input type="button" value="Add" class="ck"/>
</body>
</html>
Handling Multiplication
If you want to multiply the two numbers as opposed to adding them, simply change your operator from addition + to multiplication * :
var c = a * b;
alert("The sum is " + c);
Handling Multiple Sets of Values
If you wanted to handle multiple sets of two numbers, then you would likely want to structure your code a bit differently. Consider using a CSS class to "group" your two values and then get your results as expected :
$(function() {
$('input').on('input', function() {
// Find the closest set and recalculate it
var set = $(this).closest('.set');
// Get your values
var n1 = parseInt(set.find('.n1').val() || 0);
var n2 = parseInt(set.find('.n2').val() || 0);
// Set their result
set.find('.result').val(n1 * n2);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='set'>
<input class='n1' />*
<input class='n2' />=
<input class='result' disabled />
</div>
<div class='set'>
<input class='n1' />*
<input class='n2' />=
<input class='result' disabled />
</div>
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<script type="text/javascript" src="fuctions.js"></script>
<title>Count JS</title>
</head>
<body>
<fieldset>
<input type="number" value="1" id="num" min="1" max="5"/>
<button onclick="getValue()">
Submit
</button>
</fieldset>
</body>
</html>
JS:
function getValue() {
var x = parseInt(document.getElementById("num"));
alert(x);
}
I just want to print this value that I get using document.getElementById, but when I print appears it:
Can someone help?
.value returns value from input, in your case, you try convert DOMNode to Integer that will return NaN
var x = parseInt(document.getElementById("num").value);
Example
Add .value after document.getElementById
function getValue() {
var x = parseInt(document.getElementById("num").value);
alert(x);
}