Abdul Muqeet Abdul Muqeet - 1 month ago 6
Javascript Question

How to get the input field in nested div through jquery

I wanted to get the input field which is in div using jquery .but I am unable to to get it. I want to iterate it with class model and add into the array of string and pass it to controller.

below is my one div that have class model i will make multiple div like this and iterate it to its to get the input field in it and pass it to my controller

<div class="models">
<div class="row" >

<div class="col-md-12" >
<label class="control-label" >NIC</label>
<input type="text" class="form-control" name="VNIC" id="VNIC" required>
</div>
</div>



<div class="row">
<div class="col-md-12">
<label class="control-label">First Name</label>
<input type="text" class="form-control" name="VfirstName" id="VfirstName" required>
</div>
</div>



<script type="text/javascript">
$("#Visitor-form").on("submit", function () {
//Code: Action (like ajax...)
var slides = $(".models");
console.log(slides);
for (i = 0; i < slides.length; i++) {

var previsitor = [
{ NIC: slides[0].value, V_Name: slides[0].value }
];
}
previsitors = JSON.stringify({ 'previsitors': previsitor });
console.log(previsitors);
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/PreVisitor/addMultipleVisitor',
data: previsitors,
success: function () {
$('#result').html('"Pass List<PreVisitor>" successfully called.');
},
failure: function (response) {
$('#result').html(response);
}
});

})

Answer

Is this is what you need? Get all the input values and put them in an array. Not sure which type of array you want, just values, or values to names.

$('button').on('click',function(){
     var total = [];
     var mapped = {};
     $('.models').find('input[type="text"]').each(function(index,elem){
        total.push(elem.value);
        mapped[elem.name] = elem.value;
     });
     console.log(total);
     console.log(mapped);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="models">
            <div class="row" >

                <div class="col-md-12" >
                    <label class="control-label" >NIC</label>
                    <input type="text" class="form-control" name="VNIC" id="VNIC" required>
                </div>
            </div>



            <div class="row">
                <div class="col-md-12">
                    <label class="control-label">First Name</label>
                    <input type="text" class="form-control" name="VfirstName" id="VfirstName" required>
                </div>
            </div>
</div>
<button>click me</button>