I was wondering if someone can please help me with a jQuery script. I am using MVC 2.
I have 2 textboxes. When values a开发者_开发知识库re typed into the textboxes then the sum of these values should display in a label control as the user types. So if the page loads then the textboxes are empty so the label must also be empty (blank). When the user types in a value like 10 then 10 should display in the label. If the user types 5 into the other textbox then 15 should display. If the user clears the 2 textboxes then the label should be blank again.
I hope someone can help here :)
Thanks
$('#textbox1, #textbox2').keyup(function() {
$('#label').html('');
var val1 = $('#textbox1').val();
var val2 = $('#textbox2').val();
if(!isNaN(val1) && !isNaN(val2)) {
$('#label').html( parseInt(val1, 10) + parseInt(val2, 10) );
}
});
UPDATE
To accommodate your comment, see the changes below. Having made this change, I'm starting to lean towards Reigel's answer being the way to go, but perhaps with modification for the 0
result always being represented as an empty string.
$('#textbox1, #textbox2').keyup(function() {
$('#label').html('');
var val1 = $('#textbox1').val();
var val2 = $('#textbox2').val();
if(!isNaN(val1) || !isNaN(val2)) {
$('#label').html( (parseInt(val1, 10) || 0) + (parseInt(val2, 10) || 0) );
}
});
$("#textBox1").keydown(function(event) {
updateLabel();
});
$("#textBox2").keydown(function(event) {
updateLabel();
});
function updateLabel()
{
var val = 0;
if(isNaN($("#textBox1").val()) && isNaN($("#textBox1").val()))
{
$("#myLabel").val("");
return;
}
if(!isNaN($("#textBox1").val()))
val += $("#textBox1").val();
if(!isNaN($("#textBox2").val()))
val += $("#textBox2").val();
$("#myLabel").val(val);
}
$(document).ready(function() {
$('#num1, #num2').keyup(function(){
var num1 = parseInt($('#num1').val(),10) || 0;
var num2 = parseInt($('#num2').val(),10) || 0;
$('label.sum').text((num1 + num2)|| '')
});
});
精彩评论