![](/img/trans.png)
[英]how to get current selected div elements from same name div in jQuery?
[英]How to get current Combo / textbox id (workable on new added elements) from same name elements?
我正在使用JavaScript成功創建新行。
為了某些編程目的,我想在“ change”事件上獲取當前“ Combo”的“ index”。
但是以下代碼僅適用於第一行(頁面加載時可用),不適用於新添加的元素。 此外,它僅適用於文本框(輸入),而不適用於組合框(選擇)。 請幫忙。
使用文本框代碼(輸入標簽)-僅適用於第一行:
var textboxes = $('input[name="quantity[]"]');
textboxes.on('blur', function() {
var index = textboxes.index( this );
alert( this.value + ', ' + index );
});
將代碼用於組合(選擇標簽)-不起作用
var combos = $('combo[name="item_id[]"]');
combos.on('blur', function() {
var index = combos.index( this );
alert( this.value + ', ' + index );
});
HTML:
<select name="item_id[]" id="item_id[]" class="combo" style="width:326px;" <?php echo empty($_GET['id'])?'':'disabled';?> onchange="showAvailableQty(this.value);">
<?php $item_id=!empty($record['item_id'])?$record['item_id']:-1;echo $item_registration->fillCombo($item_id);?>
</select>
編輯:
實際上,我希望代碼不僅在下面圖片(第一行)的行上還為更改事件返回item-combo(具有相同名稱)的“索引”,還為單擊“添加行的鏈接。
如果您提供一些有效的代碼,請確保它也可以在新添加的元素上運行。 謝謝
html代碼:
<select name="item_id[]" id="item_id[]" class="combo" > option-tags </select>
謝謝,
工作提琴 。
就像現在寫的那樣,選擇器將搜索名稱為item_id[]
的標簽combo
,您只是缺少了點號.
在combo
課程之前:
var combos = $('.combo[name="item_id[]"]');
________________^
注意:您可以使用當前的模糊元素對象$(this)
來獲取index
和value
。
如果要處理動態添加到頁面的新鮮DOM,則應使用事件委托on()
希望這可以幫助。
$('body').on('blur', 'input[name="quantity[]"]', function() { var index = $('input[name="quantity[]"]').index(this); var value = $(this).val(); console.log( value + ' , ' + index ); }); $('body').on('change', '.combo[name="item_id[]"]', function() { var index = $('.combo[name="item_id[]"]').index(this); var value = $(this).val(); console.log( value + ' , ' + index ); }); $('body').append('<select name="item_id[]" id="item_id[]" class="combo" style="width:326px;"><option value="i_4">item_4</option><option value="i_4i">item_4i</option><select>'); $('body').append('<br><input name="quantity[]" type="text" value="q_4"/>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input name='quantity[]' type='text' value="q_1"/> <input name='quantity[]' type='text' value="q_2"/> <input name='quantity[]' type='text' value="q_3"/> <br> <br> <select name="item_id[]" id="item_id[]" class="combo" style="width:326px;"> <option value="i_1">item_1</option> <option value="i_1i">item_1i</option> </select> <select name="item_id[]" id="item_id[]" class="combo" style="width:326px;"> <option value="i_2">item_2</option> <option value="i_2i">item_2i</option> </select> <select name="item_id[]" id="item_id[]" class="combo" style="width:326px;"> <option value="i_3">item_3</option> <option value="i_3i">item_3i</option> </select> <br><br>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.