如何获取在 Javascript 中使用表单对象选中的复选框的值

我是 Javascript 的初学者,我的 Javascript 表单对象有问题。如何遍历整个表单对象,仅选择用户选中的元素。到目前为止,我已经尝试了以下内容:


//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");

            }

        }

    }

}

我已经为所有不同的复选框Id声明了所有var。这是一个网页:


<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>


如您所见,我已将表单放入表中。但我的问题是,每当我运行Javascript时,返回的值总是空值或未定义。我的问题是,如何在Javascript中使表单对象循环所有这些元素,最终只返回选中的复选框的值。有人可以帮我解决这个问题吗?提前致谢!!


湖上湖
浏览 100回答 1
1回答

慕妹3146593

您没有得到任何返回的原因是您的 getCbValues() 函数在您显示的代码中的任何位置都没有被调用。即使它是,它也只会显示当前状态,因为您尚未设置任何内容来响应更改。我要做的是设置事件侦听器以检测何时选中复选框,然后对该信息执行某些操作。您应该在任何功能之外执行此操作。您可以像这样设置事件侦听器:var chkMouse = document.getElementById("chkMouse");chkMouse.addEventListener('change', () => {&nbsp; &nbsp; &nbsp; &nbsp; alert('this is the mouse')&nbsp; &nbsp; &nbsp; })假设您要使用选中的数据提交表单,则可能会将项目添加到数组中,然后在提交时将其作为表单数据提交。此外,您可能希望检查是否有人取消检查您的项目。你可以这样做:chkMouse.addEventListener('change', () => {&nbsp; &nbsp; &nbsp; &nbsp; if (chkMouse.checked) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert('mouse added')&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert('mouse removed')&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; })
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript