lundi 8 juin 2020

How to get the value of checkboxes that are checked by using the form object in Javascript

I am a beginner at Javascript and I have a problem with my Javascript form objects. How do I loop through the entire form object select only the elements that are checked by the user. So far I have tried the following:

//Gets the selected checkbox values:
function getCbValues() {

    var chkMouse = document.getElementById("chkMouse");
    var chkKeyboard = document.getElementById("chkKeyboard");
    var chkDVD = document.getElementById("chkDVD");
    var chkSound = document.getElementById("chkSound");
    var myFormElem = myForm.elements;

    for (var i = 0; i < myFormElem.length; i++) {
        if (myFormElem[i].type == "checkbox") {
            if (myFormElem.checked == true) {
                if (myFormElem[i].elementId == chkMouse) {
                    alert("This is the Mouse");
                }
                if (myFormElem[i].elementId == chkKeyboard) {
                    alert("This is the Keyboard");
                }
                if (myFormElem[i].elementId == chkDVD) {
                    alert("This is the DVD");
                }
                if (myFormElem[i].elementId == chkSound) {
                    alert("This is the Sound");
                }
            } else {
                alert("Nothing");
            }
        }
    }
}

I have declared all the var for all the different checkbox Id's. Here is the html:

<form action="" name="form1">
 <!--Checkbox table-->
    <table>
        <!--Select Add on Item's-->
        <tr class="firstHeader">
            <th colspan="3">
                <h3>Select Add On Items (Optional):</h3>
            </th>
        </tr>

        <tr>
            <th colspan="2">Add On Items</th>
        </tr>

        <tr>
            <td><label>Mouse</label>
                <td><input type="checkbox" name="chkMouse" value="Mouse" id="chkMouse" price="31" /></td>
        </tr>

        <tr>
            <td><label>Keyboard</label></td>
            <td><input type="checkbox" name="chkKeyboard" value="Keyboard" id="chkKeyboard" price="42" /></td>
        </tr>

        <tr>
            <td><label>DVD Rome Drive</label></td>
            <td><input type="checkbox" name="chkDVD" value="DVD Rome Drive" id="chkDVD" price="56" /></td>
        </tr>

        <tr>
            <td><label>Sound Card</label></td>
            <td><input type="checkbox" name="chkSound" value="Sound Card" id="chkSound" price="83" /></td>
        </tr>
    </table>

As you can see I have put the form into a table. But my issue is that whenever I run the Javascript the returned value is always null or undefined. My question is that how can I make a form object in Javascript loop over all these elements and in the end only return the values of the checkboxes that are checked. Can someone help me with this issue please. Thanks in advance !!




Aucun commentaire:

Enregistrer un commentaire