js中用数组加for循环控制文本框值
js中用数组加for循环判断每个文本框的值,如果是为空就就斌值0.
文本框的名称为 tb1 tb2 tb3 tb4
我这样写的,不对.请各们帮忙
var tb1=parseInt(document.getElementById( 'tb1 ').value);
var tb2=parseInt(document.getElementById( 'tb2 ').value);
var tb3=parseInt(document.getElementById( 'tb3 ').value);
var tb4=parseInt(document.getElementById( 'tb4 ').value);
var total=parseInt(document.getElementById( 'total ').value);
var tb = new Array;
for (i = 1; i < 5; i++)
{
if (document.getElementById( 'tb[i] ').value== " ")
{
tb[i]=0;
}
}
------解决方案--------------------你是不是要实现这种效果?
var tb1=parseInt(document.getElementById( 'tb1 ').value);
var tb2=parseInt(document.getElementById( 'tb2 ').value);
var tb3=parseInt(document.getElementById( 'tb3 ').value);
var tb4=parseInt(document.getElementById( 'tb4 ').value);
var total=parseInt(document.getElementById( 'total ').value);
for (var i = 1; i < 5; i++)
{
if (document.getElementById( 'tb ' + i ).value== " ")
{
document.getElementById( 'tb ' + i).value = 0;
}
}
------解决方案-------------------- <input type= "text " id= "tb1 " value= " " onkeyup= "ChangeText() "/>
<input type= "text " id= "tb2 " value= " " onkeyup= "ChangeText() "/>
<input type= "text " id= "tb3 " value= " " onkeyup= "ChangeText() "/>
<input type= "text " id= "tb4 " value= " " onkeyup= "ChangeText() "/>
<input type= "text " id= "total " value= " "/>
function ChangeText()
{
var total = 0;
var reg = /^[+-]?\d*[.]?\d*$/;
for (i = 1; i < 5; i++)
{
var e = document.getElementById( "tb " + i.toString());
if (e.value.length > 0 && reg.test(e.value))
{
total = total + parseFloat(e.value);
}
}
document.getElementById( 'total ').value = total;
}