使用jQuery将复选框值放入隐藏的输入中 [英] Put checkbox values into hidden input with jQuery

查看:62
本文介绍了使用jQuery将复选框值放入隐藏的输入中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用所选复选框的值填充一个隐藏的输入,并在这些值之间留一个空格.我尝试了以下理论上可行的方法,但这不是…

I'd like to populate a hidden input with the values of selected checkboxes with a space between these values. I've tried the following which in theory should work but it isnt…

JS:

$(document).ready(function () {


      var vals = $(':checkbox:checked').map(function(){
         return $(this).val();
      }).get().join(',');

      // save the values to a hidden field
      $('#tags').val(vals);


});

HTML

 <form>

  <input type="checkbox" value="test1" id="test1"><label>Test</label>
  <input type="checkbox" value="test2" id="test2"><label>Test2</label>
  <input type="checkbox" value="test3" id="test3"><label>Test3</label>

  <input type="text" value="" id="tags">

</form>

有什么想法吗?

推荐答案

:checkbox已弃用

代替

$(':checkbox:checked')

使用

$('input[type="checkbox"]:checked')

document is Ready时也没有checkboxes are checked ..先设置它们,然后尝试...

Also none of the checkboxes are checked when the document is Ready .. Set them first and then try ...

HTML

  <input type="checkbox" value="test1" id="test1" checked><label>Test</label>
  <input type="checkbox" value="test2" id="test2" checked><label>Test2</label>
  <input type="checkbox" value="test3" id="test3"><label>Test3</label>
  <input type="text" value="" id="tags">

JavaScript

function Populate(){
    vals = $('input[type="checkbox"]:checked').map(function() {
        return this.value;
    }).get().join(',');
    console.log(vals);
    $('#tags').val(vals);
}

$('input[type="checkbox"]').on('change', function() {
    Populate()
}).change();

检查小提琴

Check Fiddle

这篇关于使用jQuery将复选框值放入隐藏的输入中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆