2017-04-04 5 views
1

divの2つの入力フィールドを取得してJSONとして投稿する配列にプッシュする関数を記述しようとしています。私は2番目の入力フィールドの値を見つけるためにdivをトラバースするのに問題があります。クライアントがより多くの行を追加できるようにする関数があります(div class = row id = "addInput")。Jquery Traverse入力フィールドの祖先

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:私がセクションとラベルを持っているので、兄弟姉妹が移動するための方法をイマイチと思われます。

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

答えて

0

要素ptoHoursptoDateは兄弟ではありませんが、両方があなたの行のdivの子孫です。

あなたは親の行を見つけるために.closest()を使用することができ、その後、あなたのptoHours要素を見つけることができます。

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>

+1

うわー、ありがとう!私は自分のコードを見て、どのように関係を処理していたのでしょうか。私は実際に追加された入力行を$(this).closest( 'div')で動的に削除しています。 – EJJ

関連する問題