I want to get the value of a specific sibling element using id, I build the form at run time and there are many element have the same id but in different divisions. I tried to use
$(this).siblings(“#BillNo”).val();
$(this).prev(“#BillNo”).val();
but both return undefined value
this the code at run time : commission
<div id="bill1" class="bill hide withPadding">
<h3>Bill 1</h3>
<span>
<label>Bill no</label>
<input type="text" name="billNo" class="textField" id="BillNo"/>
</span>
<span>
<label>Bill total</label>
<input type="text" name="billTotal" class="textField" id="BillTotal"/>
</span>
<span>
<input type="button" name="addBillDetails" value="Add bill items" id="addBillDetails"/>
</span>
</div>
<div id="bill2" class="bill hide withPadding">
<h3>Bill 2</h3>
<span>
<label>Bill no</label>
<input type="text" name="billNo" class="textField" id="BillNo"/>
</span>
<span>
<label>Bill total</label>
<input type="text" name="billTotal" class="textField" id="BillTotal"/>
</span>
<span>
<input type="button" name="addBillDetails" value="Add bill items" id="addBillDetails"/>
</span>
</div>
<script type="text/javascript">
$(document).ready(function() {
$("input#addBillDetails").live('click',function(){
alert($(this).siblings("#BillNo").val());
alert($(this).prev("#BillNo").val());
});
}
</script>
That limits the searches for
#BillNothe parent div. Here’s a demo.As an aside, you should reconsider your HTML.
idshould ideally be unique values. From the HTML4 specs:And from the HTML5 specs:
You can, for example, use classes to differentiate the different inputs. It would be just as easy to target them. e.g. http://jsfiddle.net/HxtfP/1/.
Alternatively, simply leave out
idand use thenameattribute for targetting: http://jsfiddle.net/HxtfP/2/