javascript - 无法通过复选框从输入类型中的 javascript 获取值

标签 javascript jquery html

//这是我正在尝试的代码,但我没有获取输入类型中的值让我知道我做错了什么

 <script type="text/javascript">
    script for getting value from checkbox
    var array = [];
    $('input[type="checkbox"]').change(function() {
          if ($(this).prop('checked')) {
            // Add the new element if checked:
            if (array.indexOf($(this).val()) < 0) {
                array.push($(this).val());
              } 
            } else {
              // Remove the element if unchecked:
              if (array.indexOf($(this).val()) >= 0) {
                  array.splice(array.indexOf($(this).val()), 1);
                }
            }
            $('#ff_elem512').val(array.join(", "));
            console.log(array);
    });

    </script>
    </head>
    <body>

       <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="checkbox" value="1" />One
    <input type="checkbox" value="2" />Two
    <input type="checkbox" value="3" />Three
    <input type="checkbox" value="4" />Four
    <input type="checkbox" value="5" />Five
    <br />
//trying to get the value here from javascript to input id
    <input type="text" id="ff_elem512" />

</body>

最佳答案

这是工作代码:

var array = [];
$('input[type="checkbox"]').change(function() {
    if ($(this).prop('checked')) {
      // Add the new element if checked:
      if (array.indexOf($(this).val()) < 0) {
          array.push($(this).val());
        } 
      } else {
        // Remove the element if unchecked:
        if (array.indexOf($(this).val()) >= 0) {
            array.splice(array.indexOf($(this).val()), 1);
          }
      }
      $('#ff_elem512').val(array.join(", "));
      console.log(array);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>

<input type="checkbox" value="1" />One
<input type="checkbox" value="2" />Two
<input type="checkbox" value="3" />Three
<input type="checkbox" value="4" />Four
<input type="checkbox" value="5" />Five
<br />

在执行 JavaScript 代码之前,您需要添加 JQuery。

关于javascript - 无法通过复选框从输入类型中的 javascript 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44154503/

相关文章:

javascript - Angular 5 中的循环依赖性错误

javascript - 有没有办法鼠标输入事件分层元素?

javascript - 使用 CSS 和 jQuery

html - 相对定位的父级与绝对定位的子级折叠后面的元素

javascript - 使用 Javascript 模拟进度条

html - 如何使用 'html5' 运行时直接将 plupload 实现到 s3?

javascript - 亚马逊购买需要 2 个用户登录

javascript - Mongoose 正在保存文档,即使我检查文档是否已经存在

javascript/jquery 菜鸟。许多音频播放器实例

jquery - 如何在jquery中验证金钱