将所有inout值作为数组并使用alert显示

时间:2017-07-31 12:01:11

标签: javascript

我想获取数组中的所有输入值并使用alert显示。请检查下面的代码。我正在通过类名“check_item”尝试警报,但在警报弹出窗口中收到未定义的错误。我的目标是显示在点击“上传”按钮

之前检查过的值
<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>

<body>

<form>
    <input type="checkbox" name="check_item" id="check_item" class="check_item" value="1">Item 1<br/>
    <input type="checkbox" name="check_item" id="check_item" class="check_item" value="2">Item 2<br/>
    <input type="checkbox" name="check_item" id="check_item" class="check_item" value="3">Item 3<br/>
    <input type="button" class="uploadExternal" value="Upload"/>

</form>


<script type="text/javascript">
    $(document).on("click", ".uploadExternal", function (e) {

        var x = document.getElementsByClassName("check_item").value;
        alert(x);

        });
</script>


</body>
</html>

1 个答案:

答案 0 :(得分:0)

使用 jQuery

&#13;
&#13;
$(document).on("click", ".uploadExternal", function(e) {
      var x = [];
      $(".check_item").each(function(index, item){
        x.push({
          index: index,
          value: item.value,
          checked: item.checked
        });
      });
      alert(JSON.stringify(x));
      console.log(x);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>

  <form>
    <input type="checkbox" name="check_item" class="check_item" value="1">Item 1<br/>
    <input type="checkbox" name="check_item" class="check_item" value="2">Item 2<br/>
    <input type="checkbox" name="check_item" class="check_item" value="3">Item 3<br/>
    <input type="button" class="uploadExternal" value="Upload" />
  </form>

</body>
</html>
&#13;
&#13;
&#13;

如果只需要检查值,则使用简单条件进行过滤:

&#13;
&#13;
$(document).on("click", ".uploadExternal", function(e) {
  var x = [];
  $(".check_item").each(function(index, item) {
    if (item.checked) {
      x.push(item.value);
    }
  });
  alert(!x.length ? 'Nothing selected ' : JSON.stringify(x));
  console.log(x);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>

  <form>

    <label><input type="checkbox" name="check_item" class="check_item" value="1">Item 1</label>
    <label><input type="checkbox" name="check_item" class="check_item" value="2">Item 2</label>
    <label><input type="checkbox" name="check_item" class="check_item" value="3">Item 3</label>
    
    <input type="button" class="uploadExternal" value="Upload"/>
  </form>

</body>

</html>
&#13;
&#13;
&#13;