简体   繁体   中英

Javascript Checkbox onClick Addition

I have a form with two check box.

Checkbox A = $1500 Checkbox B = $1500

What I want to do is, when Checkbox A is "checked", I want to display $1500 and add into hidden value. When unchecked, subtract $1500.

When both checkbox checked, I want each other to be performed addition, which means I want to have the value "$3000" in total, when one removed, subtracted accordingly.

Currently with my codes, I can make it work for one checkbox only, which means, when checkbox is checked, it will be $1500 and when one it's removed back, it's substracted. I don't know how to combine Checkbox A & Checkbox B.

Please see my codes and help me out.

HTML

<label>
    <input type="checkbox" name="Meeting" onClick="if (this.checked) { onCheck3() } else { onUncheck3() }" value="Pre-Meeting 1" id="Meeting" />
     Pre-Meeting 1
</label>
<label>
    <input type="checkbox" name="Meeting" onClick="if (this.checked) { onCheck4() } else { onUncheck4() }" value="Pre-Meeting 2" id="Meeting" />
     Pre-Meeting 2
</label>

<input type="text" name="PreMeetingAmount" readonly id="PreMeetingAmount" /><input type="hidden" name="PreMeetingAmounthidden" readonly id="PreMeetingAmounthidden" />

Javascript

function onCheck3(){  
    t = document.form1.PreMeetingAmount.value;
    t2 = 0;

    if (t == 0) {
        document.form1.PreMeetingAmount.value = 1500;
    }
}
function onCheck4(){  
    t = document.form1.PreMeetingAmount.value;
    t2 = 0;

    if (t == 0) {
        document.form1.PreMeetingAmount.value = 1500;
    }
}

function onUncheck3(){  
    t = document.form1.PreMeetingAmount.value;
    t = t - 1500;

        if (t == 0)
            document.form1.PreMeetingAmount.value = document.form1.PreMeetingAmounthidden.value;
        else 
            document.form1.PreMeetingAmount.value = t;
}    

function onUncheck4(){  
    t = document.form1.PreMeetingAmount.value;
    t = t - 1500;

        if (t == 0)
            document.form1.PreMeetingAmount.value = document.form1.PreMeetingAmounthidden.value;
        else 
            document.form1.PreMeetingAmount.value = t;
}      

You are always setting the value to 1500. You need to add 1500 rather than set it to 1500. Try changing onCheck3 and onCheck4 similar to this:

function onCheck3() {
    t = Number( document.form1.PreMeeting.value );
    document.form1.PreMeeting.value = t + 1500;
}

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