2017-04-06 52 views
1

我有一個<table>和一些行(取決於運行查詢),在那裏我可以一個單選按鈕和一些<th><input>,我想趕上那班作進一步處理<input>值,請指導我獲取的<input>元素值

我的HTML代碼

<tr> 
    <th> 
     <input type="radio" name="assignRadio"> 
    </th> 
    <th> <?= $nearestResponders[ $i ]->get('firstName') . " " . $nearestResponders[ $i ]->get('lastName'); ?></th> 
    <th> <?= $companyName; ?></th> 
    <th> <?= $nearestResponders[ $i ]->get('contactNumber'); ?></th> 
    <th> <?= $presentCity; ?></th> 
    <th><?= $distanceInKM; ?></th> 
    <input class="selectedResponder" type="hidden" value="<?= $nearestResponders[ $i ]->getObjectId(); ?>"> 
</tr> 
</table> 

我jQuery代碼

$('input[name=assignRadio]').on('change',function(){ 
    console.log($(this).val()); 
    console.log($(this).next('.selectedResponder').val()); 
    console.log($(this).closest('.selectedResponder').val()); 
    console.log($(this).find('.selectedResponder').val()); 
}); 

,你可以看到我嘗試了一些方法來獲取價值,但失敗了,所以請指教

+0

不要包含你的PHP文件,而實際上得到最終的HTML並粘貼在這裏。製作可複製的jsfiddle或snippet會有所幫助。 –

回答

1

你的問題是由於這樣,你有遍歷DOM找到你的目標元件。它不是單選按鈕的兄弟或父母,因此您嘗試的方法都不起作用。

相反,你可以使用closest()找到最近的共同的父,在tr,然後find()元素從那裏,就像這樣:

$('input[name=assignRadio]').on('change', function() { 
 
    var $selectedResponder = $(this).closest('tr').find('.selectedResponder'); 
 
    console.log($selectedResponder.val()); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table> 
 
    <tr> 
 
    <th> 
 
     <input type="radio" name="assignRadio"> 
 
    </th> 
 
    <th>Firstname Lastname</th> 
 
    <th>Company name</th> 
 
    <th>Contact number</th> 
 
    <th>Present city</th> 
 
    <th>Distance</th> 
 
    <input class="selectedResponder" type="hidden" value="foo"> 
 
    </tr> 
 
    <tr> 
 
    <th> 
 
     <input type="radio" name="assignRadio"> 
 
    </th> 
 
    <th>Firstname Lastname</th> 
 
    <th>Company name</th> 
 
    <th>Contact number</th> 
 
    <th>Present city</th> 
 
    <th>Distance</th> 
 
    <input class="selectedResponder" type="hidden" value="bar"> 
 
    </tr> 
 
</table>

+1

感謝羅裏,它的工作排的 .. –

0

這應該工作:

$('input[name="assignRadio"]').on('change',function(){ 
      console.log($('.selectedResponder').val()); 
     }); 
+1

這將選擇在表中的第一而不是一個,這是selected..I有多行,我需要在知道被點擊 –