Reputation: 155
I basically want to use javascript to have 2 textboxes that depend on each other. For example if I input a number x in textbox1, I want textbox2 to instantly update with x*2. If I input x into textbox2, I want textbox1 to be automatically updated with x/2. These values will always be numbers.
Edit: so here is my html file. Can anyone give me a hint to why it's not working?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="scripts/jquery-1.7.2.js"></script>
<script type="text/javascript">
$("#text1").keyup(function(){
$("#text2").val($(this).val() * 2);
});
$("#text2").keyup(function(){
$("#text1").val($(this).val() / 2);
});
</script>
</head>
<body>
<input type="text" name="text1" size=3 maxlength=6>
<input type="text" name="text2" size=3 maxlength=6>
</body>
</html>
Upvotes: 0
Views: 12339
Reputation: 1
In the this case, this should do it : http://jsfiddle.net/du09jhpd/
window.update = function() {
var one = document.getElementById('one'),
two = document.getElementById('two');
two.value = parseInt(one.value) * 2;
}
window.update1 = function() {
var one = document.getElementById('one'),
two = document.getElementById('two');
one.value = parseInt(two.value) / 2;
}
Upvotes: 0
Reputation: 16510
In the very simple case, this should do it (fiddle here):
// in a <script>:
window.update = function() {
var one = document.getElementById('one'),
two = document.getElementById('two');
two.value = parseInt(one.value) * 2;
}
<!-- in your HTML: -->
<input id="one" type="text" onchange="update();" />
<input id="two" type="text" />
Upvotes: 2
Reputation: 11706
Use an onchange event or a jquery change callback to update the other boxes.
Upvotes: 0
Reputation: 53291
$("#textbox1").onkeyup(function() {
$("#textbox2").val($(this).val() * 2);
});
$("#textbox2").onkeyup(function() {
$("#textbox1").val($(this).val() / 2);
});
Upvotes: 1
Reputation: 98
I'm unable to test out the exact code you'll need for this right now, but the basic idea is to put an OnKeyUp event on each box and modify the other box through the script (using getElementById or whichever method you like)
I will try to put together some code when I can if someone else doesn't get to it first.
Upvotes: 0