AbreQueVoy
AbreQueVoy

Reputation: 2316

document.getElementById("id") returns the whole object correctly but not value although there is one

The whole app looks more or less like this:

  let request = null

  function sendApiRequest() {
    request = document.getElementById("input")
    console.log(request)
    console.log(request.value)
  }
<body>
<div class="wrapper">
  <div id="input" class="box inp"><input type="text"></div>
  <div id="textbox" class="box tb"><textarea name="name" rows="8" cols="40"></textarea></div>
  <div id="send" class="box b1"><button type="button" name="button" onclick="sendApiRequest()">Send request</button></div>
  <div id="reset" class="box b2"><button type="reset" name="reset">Reset</button></div>
</div>
</body>

Clicking the button with sendApiRequest() method returns the <div> element, but no value (undefined) from the input, although there IS some text typed into the input box.

Why is this happening?

Upvotes: 0

Views: 186

Answers (1)

depperm
depperm

Reputation: 10746

The value is of input and is a child of input id. So you need to reference children[0]

  let request = null

  function sendApiRequest() {
    request = document.getElementById("input")
    console.log(request)
    console.log(request.children[0].value)
  }
<body>
<div class="wrapper">
  <div id="input" class="box inp"><input type="text"></div>
  <div id="textbox" class="box tb"><textarea name="name" rows="8" cols="40"></textarea></div>
  <div id="send" class="box b1"><button type="button" name="button" onclick="sendApiRequest()">Send request</button></div>
  <div id="reset" class="box b2"><button type="reset" name="reset">Reset</button></div>
</div>
</body>

Other possible solutions:

  • request.firstElementChild.value an alternate way of referencing the input div child element
  • request = document.querySelector("#input>input") change request to reference input inside of div
  • request = document.querySelector("#input input") ditto
  • give the input an id and query that specifically (document.getElementById("myInputId"))

Upvotes: 3

Related Questions