mercredi 23 septembre 2015

How do you reference a checkbox array name value?

I have a sequence of checkboxes and associated select lists. If the checkbox is checked I need to take the value of the corresponding select option and then change the total, but I can't seem to reference this value. Here is a simplified version of the HTML code:

<table>
<tr>
     <td>
         <input type="checkbox" name="checkboxCK[]" id="checkboxAR1" class="check" />
     </td>
     <td>
         <select name="addonR[]" class="select-colour">
            <option value="50">1 ($50)</option>
            <option value="100">2 ($100)</option>
            <option value="150">3 ($150)</option>
            <option value="200">4 ($200)</option>
         </select>
     </td>
</tr>
<tr>
     <td>
         <input type="checkbox" name="checkboxCK[]" id="checkboxAR2" class="check" />
     </td>
     <td>
         <select name="addonR[]" class="select-colour">
            <option value="50">1 ($50)</option>
            <option value="100">2 ($100)</option>
            <option value="150">3 ($150)</option>
            <option value="200">4 ($200)</option>
         </select>
     </td>
</tr>    <tr>
     <td>
         <input type="checkbox" name="checkboxCK[]" id="checkboxAR3" class="check" />
     </td>
     <td>
         <select name="addonR[]" class="select-colour">
            <option value="50">1 ($50)</option>
            <option value="100">2 ($100)</option>
            <option value="150">3 ($150)</option>
            <option value="200">4 ($200)</option>
         </select>
     </td>
</tr>
<table>
$<span id="theTotalAmount">150</span>

And the javascript code:

$("input.check:checkbox").click(function(){

//run through allcheckboxes that are checked and pull corresponding select option value     
for (var i = 0; i < document.getElementsByName('checkboxCK[]').length; i++) 
{
    //get the value of the selected option
    var s = document.getElementsByName('addonR['+i+']');
    var theAmount = s.options[s.selectedIndex].value;
    console.log(theAmount);

    //check the checkbox is checked and if so add the corresponding select value
    if(document.getElementsByName('checkboxCK['+i+']').checked)
    {
        totalCost = totalCost+document.getElementsByName('addonR['+i+']').value;
    }
}

//rewrite the html for total amount
document.getElementById("theTotalAmount").innerHTML = totalCost;

});

I am struggling to reference the s variable.. It keeps being undefined. Can anyone see why?

Or is there a better way to achieve what I am trying to do?




Aucun commentaire:

Enregistrer un commentaire