为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

湖上湖 2022-09-23 10:08:08
我是 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中使表单对象循环所有这些元素,最终只返回选中的复选框的值。有人可以帮我解决这个问题吗?提前致谢!!
查看完整描述

1 回答

?
慕妹3146593

TA贡献1820条经验 获得超9个赞

您没有得到任何返回的原因是您的 getCbValues() 函数在您显示的代码中的任何位置都没有被调用。即使它是,它也只会显示当前状态,因为您尚未设置任何内容来响应更改。


我要做的是设置事件侦听器以检测何时选中复选框,然后对该信息执行某些操作。您应该在任何功能之外执行此操作。


您可以像这样设置事件侦听器:


var chkMouse = document.getElementById("chkMouse");

chkMouse.addEventListener('change', () => {

        alert('this is the mouse')

      })

假设您要使用选中的数据提交表单,则可能会将项目添加到数组中,然后在提交时将其作为表单数据提交。


此外,您可能希望检查是否有人取消检查您的项目。你可以这样做:


chkMouse.addEventListener('change', () => {

        if (chkMouse.checked) {

          alert('mouse added')

        } else {

          alert('mouse removed')

        }

      })


查看完整回答
反对 回复 2022-09-23
  • 1 回答
  • 0 关注
  • 96 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信