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 gwas 分析-数据质控之过滤稀有突变中出现的问题
  • ¥15 没有注册类 (异常来自 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
  • ¥15 知识蒸馏实战博客问题
  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题
  • ¥15 51单片机显示器问题
  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案