Dusan Stojnic Dusan Stojnic - 2 months ago 15
HTML Question

JQuery return only one value

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.


<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"/>


<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;
if($(this).is(':checked')) {
var str = $(".checkbox").attr("value");
$.get("demo.php?item="+str, function(data, status){
sum = sum + parseInt(data);
var str = $(".checkbox").attr("value");
$.get("demo.php?item="+str, function(data, status){
sum = sum - parseInt(data);




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




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