I have some line of javascript which is works well if it gets value from the same series of names. But I have a problem later when each values passed to another page which I'd like to break down which value is belongs to. So the question is how can I change the way the script calculate the value from 'name' to 'id'. As the codes below:

   <script type="text/javascript">
        //auto commas
        function doThousands(n) {
            n = '' + n;
            if (n.length < 4) return n;
            var c = n.length % 3;
            var pre = n.substring(0, c);
            return pre + (pre.length? ',' : '') + n.substring(c).match(/\d{3}/g).join(',');
    //sub total
        function checkTotal() {
            document.cc_form.total.value = '';
            var sum = <?=$days*$_rate*$_rooms?>;
            for (i=0;i<document.cc_form.cost.length;i++) {
                if (document.cc_form.cost[i].checked) {
                    sum = sum + parseInt(document.cc_form.cost[i].value);
                }document.cc_form.total.value = doThousands(sum);

And this is the HTML:

<form name="cc_form" id="cc_form" method="post" action="/">
<label for="transfer1"><input type="checkbox" id="transfer1" name="cost" value="800" autocomplete="off" onchange="checkTotal()" /> Taxi (800 THB | 2 pax)</label><br />
<label for="transfer2"><input type="checkbox" id="transfer2" name="cost" value="1200" autocomplete="off" onchange="checkTotal()" /> Mini Van (1,200 THB | 6 pax)</label><br />
<label for="xbed"><input type="checkbox" id="xbed" name="cost" value="1200" autocomplete="off" onchange="checkTotal()" /> Extra Bed (1,200 THB)</label><br />
<input type="text" id="total" name="total" />


Recommended Answers

All 2 Replies

So the way i do it is using eval(str) function. It executes the 'str' as a command. So create strings that are similar to this:

for(int i=0 ; i < someInteger; i++){
    sum += eval("document.getElementById(" + id + ").value");

Hope this code snippet helps.


You could use document.getElementById() as fpsasm said; however, I would not use eval function. It is not a really good way to learn a language with eval; besides, it is more of hard-coding, not easy to maintain, and no error checking.

From your HTML, you may do your JS as follows...

function checkTotal() {
  var els = document.getElementsByTagName("input")
  if (els && els.length>0) {
    var debugStr = ""
    var sum = 0
    for (var i=els.length-1; i>=0; i--) {
      if (els[i].type!="checkbox") { continue; } // interest in checkbox only
      debugStr += els[i].id+":"+els[i].getAttribute('name')+":"+els[i].value+"\n"
      sum += parseInt(els[i].value,10)
    alert("Total: "+sum+"\nDebug:\n"+debugStr)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.