开发者

how to get the value of a specific sibling element using id

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="addBill开发者_如何转开发Details"/>
    </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>


$('#BillNo', $(this).closest("div.bill")).val()

That limits the searches for #BillNo the parent div. Here's a demo.


As an aside, you should reconsider your HTML. id should ideally be unique values. From the HTML4 specs:

id = name [CS]

This attribute assigns a name to an element. This name must be unique in a document.

And from the HTML5 specs:

The id attribute specifies its element's unique identifier (ID). The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.

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 id and use the name attribute for targetting: http://jsfiddle.net/HxtfP/2/


Try this, but it`s not very goods code style.

$(document).ready(function() {
   $("input[name='addBillDetails']").live('click',function(){
        alert(  $(this).parent().parent().find('#BillNo').val()  );
    });
});


To make your life easy I suggest you just add a billNo class to those fields and use the class as selector IF possible.

Otherwise:

$('#BillNo', $(this).parents(".bill")).val()


Try:

$(this).parentsUntil(".bill").find("#BillNo").val();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜