weixin_33688840 2016-10-22 13:53 采纳率: 0%
浏览 43

jQuery只返回一个值

This is my first stackoverflow question. I am working on simple ajax code. The idea is that i have multiple checkboxes. When you click on checkbox, the jquery script needs to take the value of checkbox which is pressed and send ajax request.

The problem is that whatever checkbox i pressed the value is 321 which is the first checkbox value. I am new to javascript so sorry if question is stupid or something. Thank you.

        </title>
    </head>
    <body>

    <form action="">
    <input id="321" class="checkbox" type="checkbox" name="vehicle" value="321" />I have a car<br>
      <input id="123" class="checkbox" type="checkbox" name="vehicle" value="123" /> I have a bike<br>

      <input type="submit" value="Submit"/>
    </form>

    <span></span>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
        var sum = 0;
        $(".checkbox").change(function(){
            if($(this).is(':checked')) {
                var str = $(".checkbox").attr("value");
                $.get("demo.php?item="+str, function(data, status){
                    sum = sum + parseInt(data);
                    $("span").html(sum);
                });
            }else{
            var str = $(".checkbox").attr("value");
            $.get("demo.php?item="+str, function(data, status){
                sum = sum - parseInt(data);
                $("span").html(sum);
            });
        }
    });

});

</body>
</html>
  • 写回答

1条回答 默认 最新

  • H_MZ 2016-10-22 14:09
    关注
    $(".checkbox").attr("value")
    

    is applied to all elements having the checkbox class and results in the behavior you have experienced. You need to use

    $(this).val()
    

    or

    $(this).attr("value")
    

    instead. Also, to speed up your script, inside change you can calculate $(this) like this:

    var that = $(this);
    

    and later use that.val() and that.is(':checked')

    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵