问题
I have the following code. I want to add two input fields together and output it to the page. I get as far as being able to output what is type in the input field however I can't figure how to add the two fields together and output it. I have it at http://jsfiddle.net/erick/9Dj3j/3/
Jquery
$(function() {
var output_element = $('#output_ele');
var output_element1 = $('#output_ele1');
$('#the_input_id').keyup(function() {
var their_input = $(this).val();
var firstInput = output_element.text(their_input);
});
$('#the_input_id1').keyup(function() {
var their_input1 = $(this).val();
var firstInput1 = output_element1.text(their_input1);
});
var output_total = $('#total');
var total = firstInput + firstInput1;
output_total.text(total);
});
HTML
<form method="post">
<input type="text" id="the_input_id">
<input type="text" id="the_input_id1">
</form>
<div id="output_ele">
</div>
<div id="output_ele1">
</div>
<div id="total">
</div>
回答1:
The code you posted isn't working for a couple of reasons
- On
keyUp
you assign the new values tofirstInput
andfirstInput1
which are local to the callback - The total value is calculated outside these callbacks and hence doesn't have access to those locals (the values are almost certainly
undefined
) - The total is only calculated once on startup instead of once per click
What you need to do is write a function that adds the two values together and call that from the keyUp
handler
$('#the_input_id').keyup(function() {
updateTotal();
});
$('#the_input_id1').keyup(function() {
updateTotal();
});
var updateTotal = function () {
var input1 = parseInt($('#the_input_id').val());
var input2 = parseInt($('#the_input_id1').val());
if (isNaN(input1) || isNaN(input2)) {
$('#total').text('Both inputs must be numbers');
} else {
$('#total').text(input1 + input2);
}
};
Fiddle: http://jsfiddle.net/9Dj3j/56/
回答2:
I did a little modification on the answer above and here is the final javascript:
$(function() {
$('#the_input_id, #the_input_id1').keyup(function(){
updateTotal();
});
var updateTotal = function () {
var input1 = parseInt($('#the_input_id').val());
var input2 = parseInt($('#the_input_id1').val());
if (isNaN(input1) || isNaN(input2)) {
if(!input2){
$('#total').val($('#the_input_id').val());
}
if(!input1){
$('#total').val($('#the_input_id1').val());
}
} else {
$('#total').val(input1 + input2);
}
};
var output_total = $('#total');
var total = input1 + input2;
output_total.val(total);
});
Fiddle: http://jsfiddle.net/9Dj3j/259/
来源:https://stackoverflow.com/questions/9345480/query-add-two-input-fields-together