I’m trying to serialize the checkboxes values from a form with a specific order.
The variables must follow an alphabetic order. The values order doesnt matter whenever the variables order is respected.
This is the html form:
<form>
<input type="checkbox" value="value1"/>
<input type="checkbox" value="value2"/>
<input type="checkbox" value="value3"/>
<input type="checkbox" value="value4"/>
<input type="checkbox" value="value5"/>
<input type="checkbox" value="value6"/>
<input type="checkbox" value="value7"/>
<input type="checkbox" value="value8"/>
<input type="checkbox" value="value9"/>
<input type="checkbox" value="value10"/>
</form>
<p id="results"></p>
This is jquery script:
$(document).ready(function(){
$("input:checkbox").change(function(){
var checked = $("input:checked").size();
var name_a = $("input:checked[name=a]").size();
var name_b = $("input:checked[name=b]").size();
var name_c = $("input:checked[name=c]").size();
var name_d = $("input:checked[name=d]").size();
var name_e = $("input:checked[name=e]").size();
if(name_a<1){
$(this).attr("name","a");
}else if(name_b<1){
$(this).attr("name","b");
}else if(name_c<1){
$(this).attr("name","c");
}else if(name_d<1){
$(this).attr("name","d");
}else if(name_e<1){
$(this).attr("name","e");
};
if (checked>5) {
$(this).attr("checked", false);
}
});
function showValues() {
str = $("form").serialize();
$("#results").text(str);
}
$(":checkbox").click(showValues);
$("select").change(showValues);
showValues();
});
What I expect:
a=valueX or...
a=valueX&b=valueX or...
a=valueX&b=valueX&c=valueX or...
a=valueX&b=valueX&c=valueX&d=valueX or...
a=valueX&b=valueX&c=valueX&d=valueX&e=valueX
What I dont want:
b=valueX or...
b=valueX&a=valueX or...
a=valueX&c=valueX or...
b=valueX&a=valueX&c=valueX&d=valueX&e=valueX
I hope you’ll understand what I’m looking for. Any help would be appriciated!
note: Try to randomly check and uncheck the inputs to make sure the code is working as intended.
Please let me know if I have understood the problem well:
jsfiddle