简体   繁体   English

我有代码可以使用javascript求和两个文本框值

[英]i have code it can be sum two textbox values using javascript

i have code it can be sum two textbox values using javascript but problem is that when i entered amount into recamt textbox value and javascript count again and again recamt textbox values it should be count only one time recamt textbox value not again and again? 我有代码,它可以使用JavaScript,但问题是,当我进入到量总和是两个TextBox值recamt文本框的值和javascript计数一次又一次recamt文本框的值应该只算一次recamt不是一次又一次的文本框的值?

<script type="text/javascript">
function B(){
document.getElementById('advance').value
=(parseFloat(document.getElementById('advance').value))+
(parseFloat(document.getElementById('recamt').value));
return false;
}  
</script>

<input class="input_field2" type="text" readonly name="advance" 
id="advance" value="50" onfocus="return B(0);" /><br />
<input class="input_field2" type="text" name="recamt" id="recamt">

You could keep a property on the read-only text field to keep the old value: 您可以在只读文本字段上保留一个属性以保留旧值:

function B()
{
    var adv = document.getElementById('advance'),
    rec = document.getElementById('recamt');

    if (typeof adv.oldvalue === 'undefined') {
        adv.oldvalue = parseFloat(adv.value); // keep old value
    }

    adv.value = adv.oldvalue + parseFloat(rec.value));
    rec.value = '';

    return false;
}

You're calling the sum function every time the readonly input is focused using the new value. 每次使用新值对只读输入进行聚焦时,便要调用sum函数。 If you only want it to add to the original value, you need to store it somewhere. 如果只希望将其添加到原始值,则需要将其存储在某个位置。

HTML: HTML:

<input type="text" id="advance" readonly="readonly" value="50" /><br />
<input type="text" id="recamt">

JS: JS:

var advanceBox = document.getElementById('advance');
var originalValue = advanceBox.value;

advanceBox.onclick = function() {
    this.value = parseFloat(originalValue) +
        parseFloat(document.getElementById('recamt').value);

    return false;
};

http://jsfiddle.net/hQbhq/ http://jsfiddle.net/hQbhq/

Notes: 笔记:

  • You should bind your handlers in javascript, not HTML. 您应该使用javascript而不是HTML绑定处理程序。
  • The javascript would need to exist after the HTML on the page, or inside of a window.load handler, otherwise it will not be able to find advanceBox . 该javascript必须存在于页面上的HTML 之后或window.load处理程序的内部,否则它将无法找到advanceBox

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM