[英]How to get nth div's child element value using jquery or javascript
我想獲取第4個div的子輸入元素的值。 基本上我正在檢查chekbox值,並想使用“ this”關鍵字添加關聯的輸入框值,這是我的html代碼
<div class="container">
<div class="cell-checkbox" style="float:left;margin-right:5%;">
<input type="checkbox" name="select" value="7" class="big">
</div>
<div class="cell-desc" style="float:left;margin-right:5%;width:30%;">
<!-- Content -->
</div>
<div class="cell-cart"> //input box is inside this div
<table cellpadding="0" cellspacing="0" border="0">
<tbody>
<tr>
<td align="right">
<table align="center" class="cellBuy">
<tbody>
<tr align="right">
<td width="1%">
<input type="hidden" name="buyid" id="buyid" value="7">
<input type="hidden" name="category" value="464">
<input type="hidden" name="itemid" value="">
<input name="qty" id="qty" size="6" maxlength="6" value="1" class="input"> /*want to get this input text value
</td>
<td height="20">
<div align="left">
<input type="button" class="btn-BuyOff" value="Buy" id="addtocart" name="addtocart">
</div>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
</div>
我已經嘗試了下面提到的代碼,但是它不起作用
var result = [];
$(':checkbox:checked').each(function (i) {
result.push($(this).val() + "," + $(this).parent().next().find('#qty').val());// this is for finding quantity field value
});
var strreuslt = result.join(';');
alert(strreuslt);
$(':checkbox').eq(3)
這在jquery中為您提供了第4個元素。 索引從零開始,因此.eq(3)將給出第四個孩子。
嘗試使用最接近來獲取包含兩個輸入的最接近父級,然后觸發查找
$(':checkbox:checked').each(function (i) {
result.push($(this).val() + "," + $(this).closest('.container').find('input[name="qty"]').val());
});
要么:
$(':checkbox:checked').each(function (i) {
result.push($(this).val() + "," + $(this).parent().siblings('.cell-cart').find('input[name="qty"]').val());
});
注意:如果您有多組輸入,則需要將每個組包裝在一個dom元素中,最好是ul li
您在遍歷dom時遇到問題。 $(this).parent()
不返回其中具有輸入復選框元素的div。 您應該使用類容器遍歷最近的div,然后在其中找到輸入復選框。 像這樣:
var result = [];
$(':checkbox:checked').each(function (i) {
result.push($(this).val() + "," + $(this).closest('.container').find('[name="qty"]').val());// this is for finding quantity field value
});
var strreuslt = result.join(';');
alert(strreuslt);
請改用name
,並且永遠不要對多個元素使用相同的id
:
$(this).parent().siblings('.cell-cart').find('[name=qty]').val();
如果容器包含多個<div class="cell-cart">
則使用此方法:
$(this).parent().next().next().find('[name=qty]').val();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.