mheonyae
mheonyae

Reputation: 643

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++) {
}

Upvotes: 2

Views: 484

Answers (2)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

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>

Upvotes: 3

Ruslan Nigmatulin
Ruslan Nigmatulin

Reputation: 483

If I understood you correctly you can get all input's values simply by iterating through them with jQuery:

$.each($('.col input, .col select'), function(index, item) {
    console.log('ELEMENT ID ' + $(item).attr('id') + ' VAL - ' + $(item).val());
});

of simply use serializeArray method like this:

$('input, select').serializeArray()

Working example of both ways here: https://jsfiddle.net/hc882g27/

P.S.: in pure javascript it could be done with querySelectorAll function:

var items = document.querySelectorAll('.col input, .col select');

for (var i = 0; i < items.length; i++) {
  console.log(items[i].value);
}

Upvotes: 0

Related Questions