简体   繁体   中英

Why aren't my javascript checkboxes working?

accessoryChoices = document.getElementsByName("accessories");
var accessoriesTotal;
function PressThis()
{

if (accessoryChoices[0].checked)
{
   accessoriesTotal = 56.45;


}

if (accessoryChoices[1].checked)
{
   accessoriesTotal += 115.35;

}

if (accessoryChoices[2].checked)
{
   accessoriesTotal += (7.25);

}
else 
{
   accessoriesTotal= 5.66;

}
document.getElementById('outputDiv').innerHTML= accessoriesTotal;
return;
}

I can't seem to display the proper value. If I press all the buttons together then they add up, but if I press the first button it goes to 0. If I press the bottom buttons they add up, but If press the last button first then it goes to NaN.

You never set accessoriesTotal with a value so you add undefined with a number.

function PressThis() {
    var accessoriesTotal = 0;  //<--set it to zero

And am not sure that else is what you really want. If they do not select the last one, it will set everything to 5.66. Is that what you want or should it be += ?


Based on your comment your code should be

function PressThis() {
    var accessoriesTotal = 0;
    if (accessoryChoices[0].checked) {
        accessoriesTotal += 56.45;
    }
    if (accessoryChoices[1].checked) {
        accessoriesTotal += 115.35;
    }
    if (accessoryChoices[2].checked) {
        accessoriesTotal += 7.25;
    }

    if (accessoriesTotal===0) {  // or if (!accessoryChoices[0].checked && !accessoryChoices[1].checked && !accessoryChoices[2].checked) {
       accessoriesTotal= 5.66;
    }

    document.getElementById('outputDiv').innerHTML= accessoriesTotal;
    return;
}

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