Search code examples
javascriptjquerychildren

Get ID of all child elements and its input/select data


How can I get the id of each child element and its tag name so I can save the data of each column to a string?

<div class="row">
    <div class="col-md-4">
        <input id="poz-3" placeholder="numv" type="text">
    </div>
    <div class="col-md-4">
        <input id="poz-3" placeholder="numv" type="text">
    </div>
    <div class="col-md-4">
        <select id="poz-3-s">
            <option value="1">-Pick-</option>
            <option value="2">test2</option>
            <option value="3">test3</option>
        </select>
    </div>
</div>

I've got the loop so far, but I don't know how to get the data depending on the input/select:

for (var j = 0; j < (nCols / nRows); j++) {
}

Solution

  • You could use .find('*') to get all the childs :

    $('.row').find('*').each(function(){
        //Get the id and value
    })
    

    Hope this helps.

    $('.row').find('*').each(function(){
        if($(this).prop('tagName')!='OPTION')
          console.log("id = "+$(this).prop('id')+" / value = "+$(this).val());
      else
        console.log("id = "+$(this).prop('id')+" / value = "+$(this).text());
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="row">
        <div class="col-md-4">
            <input id="poz-3" placeholder="numv" type="text" value='first input'>
        </div>
        <div class="col-md-4">
            <input id="poz-3" placeholder="numv" type="text" value='second input'>
        </div>
        <div class="col-md-4">
            <select id="poz-3-s">
                <option value="1">-Pick-</option>
                <option value="2" selected>test2</option>
                <option value="3">test3</option>
            </select>
        </div>
    </div>