如何按类获取复选框的值

时间:2015-07-01 08:25:43

标签: javascript jquery

我有一些带有类属性的复选框,现在我尝试获取值,如果它们被点击。由于某种原因,它不起作用:

使用Javascript:

(".myClass").click (function(){
            boxArr.push($(this).attr("value"));
});

HTML:

<td>
  <form action="">
    <div class="myClass">
      <label><input type="checkbox" name="box'+index+'" id="MyBox'+pageForBoxes+''+index+'" value="'+daten.identification+'" > Anzeigen
      </label>
    </div>
  </form>
</td>

2 个答案:

答案 0 :(得分:4)

使用val()

(".myClass").click (function(){
            boxArr.push($(this).val());

答案 1 :(得分:0)

尝试

var boxArr = [];
$(".myClass").click(function() {//missing $ here
  boxArr.push($(this).find('input').val());//the input is a descendant of the div so
  snippet.log(boxArr.join())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>


<form action="">
    <div class="myClass">
        <label><input type="checkbox" name="box1" id="MyBox1" value="1" />Anzeigen</label>
    </div>
</form>
<form action="">
    <div class="myClass">
        <label><input type="checkbox" name="box2" id="MyBox2" value="2" />Anzeigen</label>
    </div>
</form>
<form action="">
    <div class="myClass">
        <label><input type="checkbox" name="box3" id="MyBox3" value="3" />Anzeigen</label>
    </div>
</form>
<form action="">
    <div class="myClass">
        <label><input type="checkbox" name="box4" id="MyBox4" value="4" />Anzeigen</label>
    </div>
</form>