Darius
Darius

Reputation: 11

How do I get multiple checkbox values and send the values via ajax in jquery?

I have 4 checkboxes. All in form of;

input type="checkbox" name="Group[]" id="Group" value="uniquevalue"

I have 3 of 4 of them checked. How can I send the values that are checked in the form

"a = chkedvalue1 &b = chkedvalue2 &c = chkedvalue3"?

I'm using jquery 1.4.2

Thank you! Spent a whole day with this issue to no avail.

Upvotes: 1

Views: 8778

Answers (3)

pradeep
pradeep

Reputation: 261

<?php
$con = mysql_connect("localhost","root","");
mysql_select_db("test",$con);
$ID = $_GET['id'];
$sql = "select city_name from city where id='$id'";
$fetch = mysql_fetch_array(mysql_query($sql));
$result = explode(",",$fetch['city_name']);
?>
<html>
<body>
<form method="post" >
<input type="checkbox" name="city[]" value="Faridabad" <?php for($i=0;$i<4;$i++) if($result[$i]=='Faridabad')echo 'checked'; ?> />Faridabad
<input type="checkbox" name="city[]" value="Gurgaon" <?php for($i=0;$i<4;$i++) `if($result[$i]=='Gurgaon') echo 'checked';?>/>Gurgaon`
<input type="checkbox" name="city[]" value="Noida"<?php for($i=0;$i<4;$i++) if($result[$i]=='Noida') echo 'checked'; ?>/>Noida
<input type="checkbox" name="city[]" value="Gaziabad" <?php for($i=0;$i<4;$i++) if($result[$i]=='Gaziabad') echo 'checked'; ?>/>Gaziabad
</form>
</body>
</html>

Upvotes: 3

Nick Craver
Nick Craver

Reputation: 630379

First, remove that id attribute, it needs to be unique. Then to get the array of values you can just .serialize() the <form> like this:

var data = $("form").serialize();

Note this will produce Group[]=..., remove the [] from the name attributes if you just want Group= for each.

...or if you want the array of values, use .map(), like this:

var arr = $("input[name='Group[]']:checked").map(function() { 
            return this.value; 
          }).get();

Upvotes: 4

fire
fire

Reputation: 21531

I suggest you serialize the form.

Upvotes: 1

Related Questions