Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Div Checkboxes group by attribute without wasting too much if your time.
The question is published on by Tutorial Guruji team.
The question is published on by Tutorial Guruji team.
HI have few checkboxes with some attributes inside div. Assuming all checkboxes are checked.
<div id="osVersion"> <input type="checkbox" id="chk1" osid="1" versionid="21" /> <input type="checkbox" id="chk2" osid="2" versionid="22" /> <input type="checkbox" id="chk3" osid="2" versionid="11" /> <input type="checkbox" id="chk4" osid="1" versionid="1" /> <input type="checkbox" id="chk5" osid="3" versionid="55" /> <input type="checkbox" id="chk6" osid="2" versionid="45" /> <input type="checkbox" id="chk7" osid="3" versionid="78" /> </div>
I am able to push the attrs into a array like this
var osVersions = []; function showOutput() { $("#osVersion input:checked").each(function (i) { osVersions.push({ "osid": $(this).attr("osid"), "versionid": $(this).attr("versionid") }); // osVersions.versions.push($(this).attr("versionid")); }); }
i want to create a json object filtered based on osid in the below format
{ "osversions" : [ { "osId" : 1, "versions" : [21,1] },{ "osId" : 2, "versions" : [22,11,45] },{ "osId" : 3, "versions" : [55,78] } ], "name" : "test", "xyz":"test" }
confused on how to filter..
Answer
You can use a loop like
$('button').click(function() { var obj = { "osversions": [], "name": "test", "xyz": "test" }, tmp = {}; $("#osVersion input:checked").each(function() { var $this = $(this), osid = $this.attr('osid'); if (!tmp[osid]) { tmp[osid] = { "osId": osid, "versions": [] }; obj.osversions.push(tmp[osid]); } tmp[osid].versions.push($this.attr('versionid')) }); //here obj is a properly formatted object console.log(obj) })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="osVersion"> <input type="checkbox" id="chk1" osid="1" versionid="21" /> <input type="checkbox" id="chk2" osid="2" versionid="22" /> <input type="checkbox" id="chk3" osid="2" versionid="11" /> <input type="checkbox" id="chk4" osid="1" versionid="1" /> <input type="checkbox" id="chk5" osid="3" versionid="55" /> <input type="checkbox" id="chk6" osid="2" versionid="45" /> <input type="checkbox" id="chk7" osid="3" versionid="78" /> </div> <button>Test</button>
Demo: Fiddle
We are here to answer your question about Div Checkboxes group by attribute - If you find the proper solution, please don't forgot to share this with your team members.