简体   繁体   中英

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

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> 

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/

PS: 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM