jQuery 如何添加两个文本框值并传递给另一个文本框?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21694235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How add the two textbox value and pass to another textbox?
提问by surname
How to add my textbox 1 and 2 value and pass to textbox 3?
如何添加我的文本框 1 和 2 值并传递给文本框 3?
<input name="1" id="1" value="" >
<input name="2" id="2" value="" >
<input name="3" id="3" value="" readonly>
Here's my fiddle http://jsfiddle.net/Zy46N/6/
这是我的小提琴http://jsfiddle.net/Zy46N/6/
回答by Tushar Gupta - curioustushar
Adding Two Strings with space separated.
以空格分隔的两个字符串相加。
var input = $('[name="1"],[name="2"]'),
input1 = $('[name="1"]'),
input2 = $('[name="2"]'),
input3 = $('[name="3"]');
input.change(function () {
input3.val(input1.val() + ' ' + input2.val());
});
两个数字相加
if It's not a valid Number take it's value 0
如果它不是有效数字,则取其值 0
var input = $('[name="1"],[name="2"]'),
input1 = $('[name="1"]'),
input2 = $('[name="2"]'),
input3 = $('[name="3"]');
input.change(function () {
var val1 = (isNaN(parseInt(input1.val()))) ? 0 : parseInt(input1.val());
var val2 = (isNaN(parseInt(input2.val()))) ? 0 : parseInt(input2.val());
input3.val(val1 + val2);
});
回答by Adil
Use class selector
for textboxes
to add, use alph numeric ids
. Use parseFloat
to convert text
to number
.
使用class selector
fortextboxes
添加,使用 alph numeric ids
。使用parseFloat
转换text
到number
。
$('.common').change(function () {
$('#id3').val(parseFloat("0"+$('#id1').val()) + parseFloat("0"+$('#id2').val()));
});
回答by Farkhat Mikhalko
You can use val and change function from jquery
您可以使用 jquery 中的 val 和 change 函数
$("#1, #2").change(function(){
var val1 = $("#1").val(),
val2 = $("#2").val();
$("#3").val(val1 + val2);
});
回答by MusicLovingIndianGirl
Use this in your javascript function.
在您的 javascript 函数中使用它。
var sum=$("#txtbox1").val()+$("#txtbox2").val();
// Assign sum to third textbox
$("#txtbox3").val(sum);
回答by Amit
回答by Rohan
Try this
尝试这个
$('input').change(function() {
if($('[name="1"]').val()!=="" && $('[name="2"]').val()!=="")
{
$('[name="3"]').val(parseInt($("#1").val())+(parseInt($("#2").val())));
}
else
{
$('[name="3"]').val("");
}
});