首页 > 解决方案 > 使用表单向导检测是否单击了复选框

问题描述

我目前正在使用表单向导:

<form name="example-1" id="wrapped" action="" method="POST">
     <div id="middle-wizard">
           <div class="step">
           </div>
           <div class="step">
           </div>
           <div class="step">
                <div class="row">
                    <div class="col-md-6">
                         <ul class="data-list-2 clearfix">
                               <li><input name="information[]" id ="other_info" class="otherInfo check_radio" type="checkbox"  value="Others"><label>Others</label></li>
                         </ul>
                    </div>
                </div>
           </div>
     </div>


<div id="bottom-wizard">
            <button type="button" name="backward" class="backward"> Backward </button>
            <button type="button" name="forward" class="forward"> Forward </button>
</div>
</form>

我正在尝试检查复选框是否被选中。我做的第一件事是控制台记录复选框的 id。

控制台返回复选框,但是当我尝试在复选框 id 上创建单击函数时,单击函数不会引发控制台日志。

这是我尝试过的点击功能示例:

console.log('#other_info')
    $("#other_info").click(function(){
        if(!$(this).is(':checked'))
        {
            console.log('yes its checked')
        }
        else
        {
            console.log('no its not!!')
        }
    })

此表单使用 iCheck 自定义插件进行复选框,因此无法正常单击或更改功能。通过使用 ichecked 提供的自定义函数完成了问题的修复

标签: javascriptjqueryhtmlformwizard

解决方案


click在这种情况下,您不应使用侦听器,而应使用change侦听器。我相信它的使用效率要高得多。

这是一个代码片段作为快速外卖(工作小提琴):

document.querySelector('#wrapped').addEventListener('change', function(event) { 
  const allClicked = this.querySelectorAll('input[type="checkbox"]:checked')
  console.log(allClicked)

  console.log(`Chief, I am clicked: ${event.target}!`) // Show what is currently being clicked
})

您也可以在我的类似回复中阅读有关该主题的更多信息: 如何计算每个选中的复选框

这是一个更复杂的小提琴:https ://jsfiddle.net/mkbctrlll/yak4oqj9/159/

在里面你有 3 种可能的方法来解决你的问题。希望这可以帮助


推荐阅读