Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a hidden input with javascript

What I am attempting to do is is access hidden object in a div. What happends is a user will click on button that will then perform some task such as delete a user. This may be easier if I show what I have.

<div class="mgLine">
    <input type="hidden" name="tenentID" value="1">
    <p class="mgName">James Gear</p>
    <input type="text" class="mgBill" value="" placeholder="Post Bill Link Here">
    <a href="#" class="mgButton" onclick="alertTest(this)">Submit Bill</a>
    <a href="#" class="mgNP">Not Paid</a>
    <a href="#" class="mgButton">Change Password</a>
    <a href="#" class="mgButton">Delete User</a>
</div>

What I want the system to do is alert the value of one which it gets from the hidden field when the "submit bill" is pressed.

function alertTest(e){
//e.parentNode
window.alert(e.parentNode.getElementsByTagName("tenentID")[0]);
}

I am attempting to use JavaScript DOM to access the element. I hope this made at least some sense. There will be many of these entries on the page.

like image 909
Austin Lovell Avatar asked Sep 16 '25 12:09

Austin Lovell


1 Answers

You need to use getElementsByName instead of getElementsByTagName

function alertTest(e){
//e.parentNode
window.alert(document.getElementsByName("tenentID")[0]);
}

getElementsByTagName is for selecting elements based on its tag say div, input etc..

getElementsByName

getElementsByTagName

Realizing that you might have multiple div section and your hidden input is the first child you could use these:-

e.parentNode.getElementsByTagName("input")[0].value;

or

e.parentNode.firstElementChild.value;

if it is not the firstCHild and you know the position then you could use

e.parentNode.children(n).value; //n is zero indexed here

Fiddle

like image 196
PSL Avatar answered Sep 18 '25 08:09

PSL