Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JQuery .serialize() to combine form elements with the same name?

I have the below form input elements, each with the same name of "rating" as shown below.

<input type="checkbox" checked="checked" value="5" id="rating5_2053" name="rating">
<input type="checkbox" checked="checked" value="4" id="rating4_2053" name="rating">
<input type="checkbox" checked="checked" value="3" id="rating3_2053" name="rating">

<input type="checkbox" checked="checked" value="2" id="rating2_2053" name="rating">
<input type="checkbox" checked="checked" value="1" id="rating1_2053" name="rating">
<input type="checkbox" checked="checked" value="0" id="rating0_2053" name="rating">

When using

$form.serialize();

and submitting the form,

EDIT: Using JQuery Serialize() result and manipulating the querystring for the GET request, it ends up like the below:

&rating=5&rating=4&rating=3&rating=2&rating=1&rating=0

There is good reason for it to do this, but in my case I don't need to do that.

I wanted to know if there is a way I can configure this to do the below instead?

&rating=5,4,3,2,1,0

Thanks

like image 998
Pricey Avatar asked Feb 20 '23 07:02

Pricey


2 Answers

Here you go

var ratingData = [],
    data = $('form').find('input:not([name="rating"])').serialize();
$('form').find('input[name="rating"]').each(function(){
    ratingData.push(this.value);
});
data += '&rating='+ratingData.join(',');
console.log(data);

http://jsfiddle.net/Ejf45/1/

like image 92
Adam Merrifield Avatar answered May 15 '23 20:05

Adam Merrifield


You can try something like this :)

var ratings="rating=";

$('input[name="rating"]:checked').each(function(){ 

    var temp = $(this).val();

    ratings = ratings+ temp +",";

});

alert(ratings);​

Jsfiddle Link

like image 33
Kabilan S Avatar answered May 15 '23 22:05

Kabilan S