1

i have a javascript code which generates dynamic sub arrays.

function createArray() {

    var myArr = new Object();
    myArr[0] = createSubArray('apple');
    myArr[1] = createSubArray('Mango');
    myArr[2] = createSubArray('Pineapple');
    myArr[3] = createSubArray('Grape');
    document.getElementById("a").innerHTML = JSON.stringify(myArr);
    return myArr;

}


function createSubArray(name){
    var arr = new Object();
    elems = document.getElementsByName(name);
    for (var i=0;i<elems.length;i++){
        if (elems[i].checked){
            arr[name] =  elems[i].value;
            arr['price'] =  elems[i].getAttribute('data-price');
        }
    }
    return arr;

}

And i got the output as below

array
  0 => 
    array
      'apple' => string 'light' (length=5)
      'price' => string '10' (length=2)
  1 => 
    array
      'apple' => string 'light1' (length=5)
      'price' => string '10' (length=2)
  2 => 
    array
      'Mango' => string 'dark' (length=4)
      'price' => string '40' (length=2)
  3 => 
    array
      'Pineapple' => string 'dark' (length=4)
      'price' => string '60' (length=2)
  4 => 
    array
      'Grape' => string 'dark' (length=4)
      'price' => string '80' (length=2)

But i need to array to be like below

array
  0 => 
    array
      'apple' => string 'light' (length=5)
       0 => 
           array
            'apple' => string 'light' (length=5)
            'price' => string '10' (length=2)
       1 => 
           array
            'apple' => string 'light1' (length=5)
            'price' => string '10' (length=2)
  1 => 
    array
      'Mango' => string 'light' (length=5)
       0 => 
           array
            'Mango' => string 'light' (length=5)
            'price' => string '10' (length=2)
  2 => 
    array
      'Pineapple' => string 'light' (length=5)
       0 => 
           array
            'Pineapple' => string 'light' (length=5)
            'price' => string '10' (length=2)

so i have changed the javascript like this

function createArray()
{
    var myArr = new Object();
    var _tempa = new Array();
    var elems = document.getElementsByTagName("input");
     for (var i=0;i<elems.length;i++)
     {  if (elems[i].checked){
         _tempa.push(elems[i].getAttribute('name'));
            myArr[i] = createSubArray1(_tempa);
          }
      }
     document.getElementById("a").innerHTML = JSON.stringify(myArr);
    return myArr;
} 

function createSubArray1(namearr){

    var arr1 = new Object();
    for (var j=0;i<namearr.length;j++){
    var elems = document.getElementsByName(name[j]);
    for (var i=0;i<elems.length;i++){
        if (elems[i].checked)
        {
        arr1[elems[i].getAttribute('data-gpname')] =  createSubArray(elems[i].getAttribute('name'));
        }
    }
    }
    return arr1;
}

 function createSubArray(name){
    var arr = new Object();
    var elems = document.getElementsByName(name);
    for (var i=0;i<elems.length;i++){
        if (elems[i].checked)
        {
        arr['productname'] =  elems[i].value;
        arr['price'] =  elems[i].getAttribute('data-price');
        }
    }
    return arr;
}

After this i am getting the out put like below

[{},{}]

My Html Is Below

<form method="post">
Apple
<input type="radio" onclick="createArray()" id="one" name="apple" data-gpname="apple" data-price="10" value="light"/> Light
<input type="radio" onclick="createArray()" id="two" name="apple" data-gpname="apple" data-price="20" value="dark" /> Dark
<input type="radio" onclick="createArray()" id="one1" name="apple1" data-gpname="apple"  data-price="120" value="light2"/> Light11
<input type="radio" onclick="createArray()" id="two1" name="apple1" data-gpname="apple" data-price="210" value="dark1" /> Dark22
<input type="text" id="appleqty" name="appleqty" value="" />
<br>
Mango
<input type="radio" onclick="createArray()" id="three" name="Mango" data-gpname="Mango"  data-price="30" value="light"/> Light
<input type="radio" onclick="createArray()" id="one" name="Mango" data-gpname="Mango" data-price="40" value="dark" /> Dark
<input type="text" id="Mangoqty" name="Mangoqty" value="" />
<br>
Pine Apple
<input type="radio" onclick="createArray()" id="four" name="Pineapple" data-gpname="Pineapple" data-price="50" value="light"/> Light
<input type="radio" onclick="createArray()" id="five" name="Pineapple" data-gpname="Pineapple" data-price="60" value="dark" /> Dark
<input type="text" id="Pineappleqty" name="Pineappleqty" value="" />
<br>
Grape
<input type="radio" onclick="createArray()" id="six" name="Grape" data-gpname="Grape" data-price="70" value="light"/> Light
<input type="radio" onclick="createArray()" id="seven" name="Grape" data-gpname="Grape" data-price="80" value="dark" /> Dark
<input type="text" id="Pineappleqty" name="Pineappleqty" value="" />

<textarea name="a" id="a" cols="50"></textarea>
<input type="submit" name="se" value="se" />
</form>

I have used php json_decode to get the array Structure

3
  • 4
    Please don't write a novel but short, meaningful question… Commented Sep 18, 2012 at 10:18
  • I agree with @feeela the problem could be expressed more succinctly, perhaps by reducing the size of the test data for a start. Commented Sep 21, 2012 at 6:59
  • 2
    A well explained question is always better than a vague-short one. Also this a specific case, which means a short question is not really possible. Commented Sep 21, 2012 at 7:04

4 Answers 4

3

Updated Demo with output in Textarea: http://jsfiddle.net/zZxaR/13/

Note: Added a couple of methods to pretty print the array in the console

Disclaimer: Used a bit of jQuery to make the traversal easier. Can be done just as easily without using it too.

Code:

function createArray() {
    var myArray = [], i = 0, temp;
    while(i < 4) myArray[i++] = [];
    myArray[0]['apple'] = '';
    myArray[1]['mango'] = '';
    myArray[2]['grape'] = '';
    myArray[3]['pineapple'] = '';

    $('input[data-gpname]:checked').each(function() {
        var gp = $(this).attr('data-gpname').toLowerCase();
        for(i = 0; i < 4; i++) {
            if(myArray[i][gp] != undefined) {
                myArray[i][gp] = $(this).attr('value');
                temp = [];
                temp[gp] = $(this).attr('value');
                temp['price'] = $('#' + gp + 'qty').val();
                myArray[i].push(temp);
            }
        }
    });

    console.log(myArray);
    prettyPrint(myArray);
}
Sign up to request clarification or add additional context in comments.

3 Comments

why does this answer contain canc... I mean jQuery?
just to make the traversal a little easy. it can easily be done without too. there is a disclaimer for jquery usage right at the beginning of the answer. :-)
2
+50

Hope this will help you. The output is same like you told here.

The source of this page is here.

I made a another sample based on your comments. Try this and let me know.

HTML:

<form method="post" id="myform">
Apple
<input type="radio" onclick="constructJSON(this.name)" id="one" name="apple" data-gpname="apple" data-price="10" value="light"/> Light
<input type="radio" onclick="constructJSON(this.name)" id="two" name="apple" data-gpname="apple" data-price="20" value="dark" /> Dark
<input type="radio" onclick="constructJSON(this.name)" id="one1" name="apple1" data-gpname="apple"  data-price="120" value="light2"/> Light11
<input type="radio" onclick="constructJSON(this.name)" id="two1" name="apple1" data-gpname="apple" data-price="210" value="dark1" /> Dark22
<input type="text" id="appleqty" name="appleqty" value="" />
<br>
Mango
<input type="radio" onclick="constructJSON(this.name)" id="three" name="Mango" data-gpname="Mango"  data-price="30" value="light"/> Light
<input type="radio" onclick="constructJSON(this.name)" id="one" name="Mango" data-gpname="Mango" data-price="40" value="dark" /> Dark
<input type="text" id="Mangoqty" name="Mangoqty" value="" />
<br>
Pine Apple
<input type="radio" onclick="constructJSON(this.name)" id="four" name="Pineapple" data-gpname="Pineapple" data-price="50" value="light"/> Light
<input type="radio" onclick="constructJSON(this.name)" id="five" name="Pineapple" data-gpname="Pineapple" data-price="60" value="dark" /> Dark
<input type="text" id="Pineappleqty" name="Pineappleqty" value="" />
<br>
Grape
<input type="radio" onclick="constructJSON(this.name)" id="six" name="Grape" data-gpname="Grape" data-price="70" value="light"/> Light
<input type="radio" onclick="constructJSON(this.name)" id="seven" name="Grape" data-gpname="Grape" data-price="80" value="dark" /> Dark
<input type="text" id="Pineappleqty" name="Pineappleqty" value="" />

<textarea name="a" id="a" cols="50"></textarea>
<input type="submit" name="se" value="se" />

</form>

Script:

var rgArray = [];
function constructJSON(name)
{
  rgArray.push(name);
  var myArray = {};
  var productData = {};
  productData['products'] = createArray();
  $("#a").html(JSON.stringify(productData));
}

function createArray(){
  var group = {};
  var product;
  var data;
  var hasValue = false;
  $rgArray = $(rgArray);
  $.each($rgArray, function(i, gp){
    product = {};
    var el = "input[data-gpname='"+gp+"']";
    $el = $(el);
    hasValue = false;
    $.each($el, function(i, item){
      
      if(item.checked){
          data = {};
          data.name = $(item).val();
          data.price = $(item).attr("data-price");
            
          hasValue = true;
          product[$(item).attr("name")] = data;
        }
    });
    if(hasValue) group[gp] = product;
  });
  return group;
}

5 Comments

ok its working but this line var rgArray = ['apple', 'Mango', 'Pineapple', 'Grape']; should be dynamic the array value should be given from the radio button name variable
Is there any specific reason for getting radio button name dynamic?
because all the radio buttone is generated dynimicaly
ok, you want to generate the json for all the radio buttons which are selected at once? I don't think you can get all at once. You can generate the output for what is currently selected if everything is dynamic.
if any check box is selected in that i will provide a variable name called as data-proname for var rgArray i need that value to be inserted in rgArray
1

For the multi sub array I created an example and code here

Bellow is just FYI:

In jQuery form serialize array function is used to print/show the values in array format.

$('form').submit(function() {
  console.log($(this).serializeArray());
  return false;
});

1 Comment

i think you dont understand the question
-1

try this code i have just edited it a little

function createSubArray(name){
    var arr = [];

    elems = document.getElementsByName(name);
    for (var i=0;i<elems.length;i++){
        if (elems[i].checked){
            var o = {}
            o[name] =  elems[i].value;
            o['price'] =  elems[i].getAttribute('data-price');
            arr.push(o);
        }
    }
    return arr;

}
function createArray() {

    var myArr = [];
    myArr[0] = createSubArray('apple');
    myArr[1] = createSubArray('Mango');
    myArr[2] = createSubArray('Pineapple');
    myArr[3] = createSubArray('Grape');
    document.getElementById("a").innerHTML = JSON.stringify(myArr);
    return myArr;
}

earlier you were returning an object from the createSubArray method which i think was the mistake
i have edited it to return an array with all the objects

this is the JSON string that i was getting

[
    [
        {
            "apple": "light",
            "price": "10"
        },
        {
            "apple": "dark",
            "price": "20"
        }
    ],
    [
        {
            "Mango": "light",
            "price": "30"
        },
        {
            "Mango": "dark",
            "price": "40"
        }
    ],
    [
        {
            "Pineapple": "light",
            "price": "50"
        },
        {
            "Pineapple": "dark",
            "price": "60"
        }
    ],
    [
        {
            "Grape": "light",
            "price": "70"
        },
        {
            "Grape": "dark",
            "price": "80"
        }
    ]
]

6 Comments

ok i think the top level object should have been an array too.. i have edited my ans and the response string that i was getting have a look
not its not the correct answer check here i need like this jsfiddle.net/yJkEE
kindly check the question where 'But i need to array to be like below' is written
yeah i have seen that.. i think that is also not correct. can you please add a valid JSON string to teh question like the one you want?
the above is not an json its an array
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.