User97798 User97798 - 5 months ago 10
JSON Question

jQuery each function is not working and unable to create json string

I am trying create a json string. i have to get all element value from html with class and name. I am using jQuery

HTML

<div id="PackageBuilder-AddPax-Main">
<div class="PackageBuilder-AddPax">
<div>
<input type="text" name="input1" value="A1">
<div class="HotelSearchFrom-div-input2">
<input type="text" name="input2" value="1">
<input type="text" name="input2" value="2">
</div>
</div>
</div>
<div class="PackageBuilder-AddPax">
<div>
<input type="text" name="input1" value="A2">
<div class="HotelSearchFrom-div-input2">
<input type="text" name="input2" value="3">
<input type="text" name="input2" value="4">
</div>
</div>
</div>
<div class="PackageBuilder-AddPax">
<div>
<input type="text" name="input1" value="A3">
<div class="HotelSearchFrom-div-input2">
<input type="text" name="input2" value="5">
<input type="text" name="input2" value="6">
</div>
</div>
</div>
</div>
<input type="submit" onclick="Make_String()">


I have to make string like this but i am not be able to make it.

[{"Input1":A1,"Input2":[1,2]},{"Input1":A2,"Input2":[3,4]},{"Input1":A3,"Input2":[5,6]}]


Below Code i am using

function Make_String(){
var RoomGuests = [];
var j = 0;
$('#PackageBuilder-AddPax-Main').find('[name="input1"]').each(function(i){
var NoOfAdults_Val = $('[name="input1"]').val()
var input2array = [];
$('#HotelSearchFrom-div-input2').find('[name="input2"]').each(function() {
alert($(this).val());
input2array.push($(this).val());
});
RoomGuests[j] = [];
RoomGuests[j]['Input1'] = NoOfAdults_Val;
RoomGuests[j]['Input2'] = input2array;
j++
});
}

Answer

You can do with jQuery each() and map().

each() Method

function Make_String() {
    array = [];

    $('.PackageBuilder-AddPax').each(function(i,e) {
        $(this).find('.HotelSearchFrom-div-input2').each(function(i,e) {
            inputarray2 = [];
            $(this).find('[name="input2"]').each(function(i,e) {
                inputarray2.push($(e).val());
            })
        })

        str = {
            'Input1': $(this).find('[name="input1"]').val(),
            'Input2': inputarray2
        }
        array.push(str);
    });

    console.log(array);
    var jsonstring = JSON.stringify(array);
    console.log(jsonstring);
}

OR

map() Method

function Make_String() {
    var array = $('.PackageBuilder-AddPax').map(function() {
        return {
            'Input1': $(this).find('[name="input1"]').val(),
            'Input2': $(this).find('[name="input2"]').map(function() {
                return this.value;
            }).get()
        }
    }).get();
    console.log(array);
    var jsonstring = JSON.stringify(array);
    console.log(jsonstring);
}
Comments