简体   繁体   中英

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?

<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. If you only want it to add to the original value, you need to store it somewhere.

HTML:

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

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/

Notes:

  • You should bind your handlers in javascript, not 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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