I have a radio button like below
Apple
<input type="radio" id="one" name="apple" data-price="10" value="light"/> Light
<input type="radio" id="two" name="apple" data-price="20" value="dark" /> Dark
<input type="text" id="appleqty" name="appleqty" value="" />
Mango
<input type="radio" id="three" name="Mango" data-price="30" value="light"/> Light
<input type="radio" id="one" name="Mango" data-price="40" value="dark" /> Dark
<input type="text" id="Mangoqty" name="Mangoqty" value="" />
Pine Apple
<input type="radio" id="four" name="Pineapple" data-price="50" value="light"/> Light
<input type="radio" id="five" name="Pineapple" data-price="60" value="dark" /> Dark
<input type="text" id="Pineappleqty" name="Pineappleqty" value="" />
Grape
<input type="radio" id="six" name="Grape" data-price="70" value="light"/> Light
<input type="radio" id="seven" name="Grape" data-price="80" value="dark" /> Dark
<input type="text" id="Pineappleqty" name="Pineappleqty" value="" />
I this i need to create a array like below
array
0 =>
array
'apple' => string 'light' (length=10)
'price' => string '50' (length=1)
1 =>
array
'Pineapple' => string 'dark' (length=10)
'price' => string '60' (length=1)
A Kind Note : the array key should be the radio button name, the price should be taken from data-price in radio button and i need to serilize this array
This should be done using javascript.
You’ll need to iterate the
<input>s. In order to do so:If you know beforehand the element
names you’ll be looking for (i.e.apple,Mango, and so on), you can dodocument.getElementsByNameon each of those names, as explained in In JavaScript, how can I get all radio buttons in the page with a given name?.If you don’t know them (they are dynamic), just wrap them in a
<div>with a given id and iterate its children, as in how to loop through some specific child nodes.While iterating the radios of a given
name, inspect thecheckedproperty of each in order to know which of them is selected, as in How can i check if a radio button is selected in javascript?.You’ll want to build an associative array with keys the following key-value pairs, as in Dynamically creating keys in javascript associative array:
<input>‘snameandvalueattributes.priceanddata-priceattribute. You’ll need to usegetAttribute('data-price')to get thedata-priceattribute’s value.Example:
You can see this example working in this JSFiddle.