Reputation: 57
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>
Upvotes: 0
Views: 2010
Reputation: 1661
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>
Upvotes: 1
Reputation: 14541
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="">
Upvotes: 0