我想获取复选框值

时间:2019-09-26 13:21:09

标签: javascript

它总是说List<Property> properties = Arrays.asList(new Property("aaa", "1"), new Property("bbb", "2")); ListDataProvider<Property> dataProvider = DataProvider.ofCollection(properties); Grid<Property> grid = new Grid<>(Property.class); grid.setDataProvider(dataProvider); private void updateFieldByName(final String name, final String value) { properties.stream().filter((o) -> o.getName().equals(name)).forEach((p) -> { p.setValue(value); dataProvider.refreshAll(); }); } public static class Property { private String name; private String value; public Property(final String name) { this(name, "-"); } public Property(final String name, final String value) { super(); this.name = name; this.value = value; } public String getName() { return name; } public void setName(final String name) { this.name = name; } public String getValue() { return value; } public void setValue(final String value) { this.value = value; } @Override public String toString() { return "[" + name + " = " + value + "]"; } } ,这是我遇到的错误...

我想从复选框Value ...中获取价值

if (checks[i].checked === true )
function submitFun() {
  var checks = document.getElementsByClassName('checks')
  var str = "";
  for (let i = 0; i < 3; i++) {

    if (checks[i].checked === true) {
      str += checks[i].value + "";
    }
  }
  alert(str);
}

3 个答案:

答案 0 :(得分:1)

当您有两(2)个复选框时,您要迭代三(3)次,到循环结束时,i将是2,而check[2]是{{1 }},而不是undefinedi < checks.length

i < 3
function submitFun() {
  var checks = document.getElementsByClassName('checks')
  var str = "";

  for (let i = 0; i < checks.length; i++) {
    if (checks[i].checked === true) {
      str += checks[i].value + " ";
    }
  }
  alert(str);
}

答案 1 :(得分:0)

也使用querySelectorAll来选中所有复选框,还可以在for循环中使用checks.length来防止数组上的空指针

请参见下面的工作片段

function submitFun() {
  var checks = document.querySelectorAll('.checks')
  var str = "";
  for (let i = 0; i < checks.length; i++) {

    if (checks[i].checked === true) {
      str += checks[i].value + "";
    }
  }
  alert(str);
}
<div class="container">

  <input type="checkbox" class="checks" value="뜨거워"> hot
  <input type="checkbox" class="checks" value="추워"> clod
  <a href="#" onclick="submitFun();return false;">ok </a>

</div>

答案 2 :(得分:0)

尝试一下。

  1. 避免在HTML中附加事件(不建议使用)
  2. 在迭代时使用array.length,或者最好使用Array.forEach()

function submitFun() {


    var checks = document.getElementsByClassName('checks')
    var str = "";
    

    for (let i = 0; i < checks.length; i++ ){

        if (checks[i].checked === true ) {
             str += checks[i].value + "";
         }
     }
     alert(str);
}

document.querySelector('a').addEventListener('click', () => {
	submitFun();
});
<div class = "container">

    <input type="checkbox" class ="checks" value ="뜨거워"> hot
    <input type="checkbox" class ="checks" value ="추워"> clod
    <a href="#">ok </a>

</div>