简体   繁体   中英

how to fetch values of two hidden tags with different id

I have using two anchor tag to transfer the control to same page. and gives two hidden input with same id but different values. as shown in given code.

 <li data-icon="false"><a href="#paymentReceiptVoucher" onclick="loadAccForPayVoucher();">
        <input type="hidden" id="PRVou" value="payment">PaymentReceipt Voucher</a></li>

<li data-icon="false"><a href="#paymentReceiptVoucher" onclick="loadAccForPayVoucher();">
        <input type="hidden" id="PRVou" value="receipt">ReceiptPayment Voucher</a></li>

and i want to get the values of these hidden tags by using following javascript code.

loadAccForPayVoucher = function() {
    alert(document.getElementById('PRVou').value);
}

and it always alert payment . how can i get the value according to the link. Thanks.

id attributes are meant to be unique, regardless of their context. There should only be one element in the entire document with a given id .

Give the element a class name instead:

<input type="hidden" class="PRVou" value="payment">

And then use getElementsByClassName :

document.getElementsByClassName('PRVou')[0].value

Try this:

<li data-icon="false"> <a href="#paymentReceiptVoucher" onclick="loadAccForPayVoucher('payment');">
        <!--<input type="hidden" id="PRVou" value="payment">PaymentReceipt Voucher</a> --></li>

<li data-icon="false"><a href="#paymentReceiptVoucher" onclick="loadAccForPayVoucher('receipt');">
        <!-- <input type="hidden" id="PRVou" value="receipt">ReceiptPayment Voucher</a> --></li>
<script type="text/javascript">
    loadAccForPayVoucher = function(type) {
        alert(type);
        //alert(document.getElementById('PRVou').value);
    }
</script>

In HTML the ID attributes are always unique, thus when you call document.getElementById , the DOM of the browser will go out and fetch any (most likely the first) element with the given ID.

What can I do?

Give them separate IDs, your html will look like this:

<li data-icon="false"><a href="#paymentReceiptVoucher" onclick="loadAccForPayVoucherPayment();">
     <input type="hidden" id="PRVou-payment" value="payment"/>PaymentReceipt Voucher</a></li>

<li data-icon="false"><a href="#paymentReceiptVoucher" onclick="loadAccForPayVoucherReceipt();">
    <input type="hidden" id="PRVou-receipt" value="receipt"/>ReceiptPayment Voucher</a></li>

And then your JavaScript will have separate event handlers:

loadAccForPayVoucherPayment = function() {
    alert(document.getElementById('PRVou-payment').value);
}
loadAccForPayVoucherReceipt = function() {
    alert(document.getElementById('PRVou-receipt').value);
}

Update : I made you a fiddle :) http://jsfiddle.net/YCXC8/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM