jquery获取复选框选中的值

文章描述:

使用按钮submit提交表单后可以获取复选框的值,但是这样的体验可能有点不好,如何用jQuery获取复选框checkbox值?

<div class="container">
  <h4>你的爱好:</h4>
  <input type="checkbox" class="check-ui" name="hobby" value="看书" />
  <span>看书</span>
  <input type="checkbox" class="check-ui" name="hobby" value="绘画" checked />
  <span>绘画</span>
  <input type="checkbox" class="check-ui" name="hobby" value="旅游" />
  <span>旅游</span>
  <input type="checkbox" class="check-ui" name="hobby" value="打篮球"/>
  <span>打篮球</span>
  <input type="checkbox" class="check-ui" name="hobby" value="打游戏"/>
  <span>打游戏</span>
  <input type="checkbox" class="check-ui" name="hobby" value="听歌"/>
  <span>听歌</span>
  <div>
    <input type="button" class="btn-ui bc" value="提交"/>
  </div>
</div>
.check-ui {
    width: 16px;
    height: 16px;
    border: 1px solid #d2d2d2;
    background: #fff;
    font-size: 12px;
    border-radius: 2px;
    transition: .1s linear;
    text-align: center;
}
.btn-ui {
    display: inline-block;
    height: 38px;
    line-height: 38px;
    padding: 0 18px;
    background-color: #1E9FFF;
    color: #fff;
    white-space: nowrap;
    text-align: center;
    font-size: 14px;
    border: none;
    border-radius: 2px;
    cursor: pointer;
    outline: none;
    -webkit-transition: all .3s;
    box-sizing: border-box;
    margin-top: 30px;
}
h4 {
    padding: 10px 0;
}
span {
    padding: 0 5px;
}
$('.bc').on('click',function(){
    var $box = $("[name='hobby']:checked"), val = '';
        $.each($box,function (i,v){
            val += i > 0 ? ","+v.value : v.value;
        });
        console.log(val);
         
})

 

发布时间:2022/10/13

发表评论