EJJ
EJJ

Reputation: 805

Jquery Traverse Ancestors for input fields

I am trying to write a function that will grab the 2 input fields in the div and push them to an array which I will post as JSON. I am having trouble traversing the div to find the value of the 2nd input field. I have a function that will allow the client to add more rows(div class = row id="addInput").

HTML:

<div class="testList" id = wrapper>
<div class="row" id="addInput" >
    <section class="col col-4">
         <label class="input"> <i class="icon-append fa fa-calendar"></i>
            <input type="date" class="ptoDate" name="startDate" id="startDate" placeholder="Request Date">
         </label>
    </section>
    <section class="col col-2">
        <label class="input"><i class="icon-append fa fa-clock-o"></i>
            <input class="ptoHours" min="0" max="8" type="number" name="hour" id="hour" placeholder="Hours">
        </label>
    </section>
    <section class="col col-2">
        <a id="addField" title="Add More Fields" class="btn btn-primary" onclick="addInput('wrapper');">&nbsp;+&nbsp;</a>
    </section>
</div>

JS: It appears that since I have sections and labels, siblings isnt the way to go.

var timeoffRequests = [];

$("input[class = ptoDate]").each(function(){

    var date = $(this).val();
    var hours = $(this).siblings('.ptoHours').val();

    item ={};
    item['date'] = date;
    item['hours'] = hours;

    timeoffRequests.push(item);
})

Upvotes: 1

Views: 72

Answers (1)

gaetanoM
gaetanoM

Reputation: 42054

The elements ptoHours and ptoDate are not siblings, but both are descendent of your row div.

You can use .closest() in order to find the parent row and then you can find your ptoHours element:

var timeoffRequests = [];

$(".ptoDate").each(function(idx, ele){

    var date = $(ele).val();;
    var hours = $(ele).closest('.row').find('.ptoHours').val();

    item ={};
    item['date'] = date;
    item['hours'] = hours;

    timeoffRequests.push(item);
})



console.log(timeoffRequests);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div class="testList" id=wrapper>
    <div class="row" id="addInput">
        <section class="col col-4">
            <label class="input"> <i class="icon-append fa fa-calendar"></i>
                <input type="date" class="ptoDate" name="startDate" id="startDate" placeholder="Request Date">
            </label>
        </section>
        <section class="col col-2">
            <label class="input"><i class="icon-append fa fa-clock-o"></i>
                <input class="ptoHours" min="0" max="8" type="number" name="hour" id="hour" placeholder="Hours">
            </label>
        </section>
        <section class="col col-2">
            <a id="addField" title="Add More Fields" class="btn btn-primary" onclick="addInput('wrapper');">&nbsp;+&nbsp;</a>
        </section>
    </div>
</div>

Upvotes: 1

Related Questions