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')

    评论

    报告相同问题?

    悬赏问题

    • ¥30 c++类和数组实验代码
    • ¥20 C语言字符串不区分大小写字典排序相关问题
    • ¥15 关于#python#的问题:我希望通过逆向技术爬取1688搜索页下滑加载的数据
    • ¥15 关于Linux的终端里,模拟实现一个带口令保护的屏保程序遇到的输入输出的问题!(语言-c语言)
    • ¥15 请问,这个嵌入式Linux系统怎么分析,crc检验区域在哪
    • ¥15 二分类改为多分类问题
    • ¥15 Unity微信小游戏上调用ReadPixels()方法报错
    • ¥15 如何通过求后验分布求得样本中属于两种物种其中一种的概率?
    • ¥15 q从常量变成sin函数,怎么改写python代码?
    • ¥15 图论编程问题,有可以指导的吗