javascript - JQUERY: Storing div ID and checked value into a multidimensional array -
i want store div id , checked value array.
suppose check samsung , lenovo brands , 4gb ram, array should be:
array[ ] = ["brands" => "samsung,lenovo" , "ram" => "4gb"]
html
<div id="brand"> <input type="checkbox" class="chkbx" value="samsung">samsung<br> <input type="checkbox" class="chkbx" value="nikon">nikon<br> <input type="checkbox" class="chkbx" value="lenovo">lenovo<br> <input type="checkbox" class="chkbx" value="alcatel">alcatel<br> </div> <div id="ram"> <input type="checkbox" class="chkbx" value="2 gb">2 gb<br> <input type="checkbox" class="chkbx" value="3 gb">3 gb<br> <input type="checkbox" class="chkbx" value="5 gb">5 gb<br> <input type="checkbox" class="chkbx" value="6 gb">6 gb<br> </div>
the divs dynamically grabbed server. illustration, there multiple divs , id's of them not known.
appreciated.
in advance.
try utilizing object
having properties same element id
, set property having same name element id
selected input
value
var res = { "brand": "", "ram": "" }; $("#brand, #ram").on("change", function(e) { var val = e.target.value; // if `e.target.value` `val` begins character `a-z` , case insensitive // set `brand` property of `res` `val` , // else set `ram` property `val` res[/^[a-z]/i.test(val) ? "brand" : "ram"] = e.target.value; console.log(res); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <div id="brand"> <input type="checkbox" class="chkbx" value="samsung">samsung <br> <input type="checkbox" class="chkbx" value="nikon">nikon <br> <input type="checkbox" class="chkbx" value="lenovo">lenovo <br> <input type="checkbox" class="chkbx" value="alcatel">alcatel <br> </div> <div id="ram"> <input type="checkbox" class="chkbx" value="2 gb">2 gb <br> <input type="checkbox" class="chkbx" value="3 gb">3 gb <br> <input type="checkbox" class="chkbx" value="5 gb">5 gb <br> <input type="checkbox" class="chkbx" value="6 gb">6 gb <br> </div>
Comments
Post a Comment