无法在Jquery中获得复选框值?

时间:2018-10-08 18:24:36

标签: javascript jquery

我正在使用jquery动态创建复选框,然后将这些复选框附加在div标签内。现在,我想在单击按钮时获得复选框的值,但是由于某种原因,我只获得“开”而不是实际值。我可能做错了什么?

HTML:

<div class="checkboxes">
  <label>Select a category</label><br>
</div>


<button style="background-color: #e7e7e7; color: black; border: none;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;" id="clr_btn">Clear
            </button>

JavaScript:

   $(document).ready(function () {

        $.ajax({
            url: "/getcategory",
            type: "GET",

            success: function (result) {
                var result = result.results;

                if (result.length > 0) {


                    $.each(result, function (i, res) {
                        var $chk = $('<input type="checkbox" class="chklist" name="chke"  id="chk_'+i+'" val ='+res.name+'/>'+res.name+"<br />");
                        $('.checkboxes').append($chk)


                    });



                }


            },
            error: function (error) {


            }
        });
    })


// button click event

  $('#clr_btn').click(function (e) {


  alert($("input[name=chke]:checked").map(
     function () {return this.value;}).get().join(","));

    })

1 个答案:

答案 0 :(得分:1)

在您的HTML文字字符串中,您未设置元素的value,而是未设置val属性。

// Dummy variable to make loop run
let result = [{name:"foo"},{name:"bar"},{name:"baz"}];

$.each(result, function (i, res) {
  var $chk = $('<input type="checkbox" class="chklist" name="chke"'  
                + 'id="chk_' + i + '" value =' + res.name + '>' + 
                res.name + "<br />");
  $('.checkboxes').append($chk)
});

// JQuery recommends using ".on()" to bind events now:
$('#clr_btn').on("click", function (e) {
  alert($("input[name='chke']:checked").map(
    function () {return this.value;}).get().join(","));
});
#clr_btn {
        background-color: #e7e7e7; 
        color: black; border: none;
        padding: 15px 32px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkboxes">
  <label>Select a category</label><br>
</div>

<!-- Don't use inline CSS. -->
<button id="clr_btn" type="button">Clear</button>