Koen van de Sande
Koen van de Sande

Reputation: 223

Javascript: Loop through class and push the inputs

I'm having a problem with pushing some input values to an array. I have a div with a class optiondiv that can be cloned. This div has some table rows with some input fields as follows:

<div class="optiondiv">
    <table class="tableOptions">
        <tr>
            <td>
                <input type="text" class="title">
            </td>

            <td>
                <input type="text" class="position">
            </td>
            <td>
                <select class="input">
                    <option value="1">Drop-down</option>
                    <option value="2">Radio Buttons</option>
                    <option value="3">Checkbox</option>
                    <option value="4">Multiple Select</option>
                </select>
            </td>
            <td>
                <input type="checkbox" class="required"> Required?
            </td>
        </tr>
        </tbody>
    </table>
</div>

I'm trying to get all the input fields of the option, for each option and then push them to an array. The problem is that there's no 'split' between each option. If I use console.log();, the values will be printed like this: [Doors, 1, Windows, 5] but what I really want is

[0][Doors, 1]
[1][Windows, 5]

This is de code that I'm using:

$('.generateString').click(function (e)
    {
        e.preventDefault();
        $('.optiondiv').each(function(){
            var arrText = new Array();

            $('input[type=text]').each(function ()
            {
               if($(this).val() != ''){
                   // arrText.push('nietleeg');
                   arrText.push($(this).val());
                }
            })
            console.log(arrText);
        })

    });

Happy coding!

Upvotes: 0

Views: 1694

Answers (1)

Vara Prasad
Vara Prasad

Reputation: 497

First of all, instead of

$('input[type=text]').each(function ()

you need to use this for fetching input elements inside each .optiondiv

$(this).find('input[type=text]').each(function ()

And for your requirement, just define the array variable outside and create associative array inside the each loop like below

$('.generateString').click(function(e) {
    e.preventDefault();
    var arrText = new Array();
    $('.optiondiv').each(function(i) {
        if (typeof arrText[i] == "undefined")
            arrText[i] = new Array();

        $(this).find('input[type=text]').each(function() {
            if ($(this).val() != '') {
                // arrText.push('nietleeg');
                arrText[i].push($(this).val());
            }
        })
        console.log(arrText[i]);
    })

    console.log(arrText);

});

Upvotes: 1

Related Questions