Kathy
Kathy

Reputation: 107

input value returns null

HTML:

    <div class="form-group">
      <input class="input-sol form-control" id="focusedInput appendedInput sol" placeholder="Enter number" type="text" required>
      <button class="btn btn-warning btn-large" id="submit" type="button" onClick="getUserChoice()">Get Images</button>
    </div>

JavaScript:

    function getUserChoice() {
      var user_sol = document.getElementById("sol").value;

...

When I enter a value and click the button, my function is triggered but in console I get the following error:

    Uncaught TypeError: Cannot read property 'value' of null
      at getUserChoice (index.js:44)
      at HTMLButtonElement.onclick (index.html:53)

The other values selected from a drop-down list are fine but not for this input.

Upvotes: 0

Views: 9967

Answers (3)

Tornike Shavishvili
Tornike Shavishvili

Reputation: 1354

please see following answer Can an html element have multiple ids?

You can not have multiple id-s on an html element. The input's id isn't "sol" and that's why document.getElementById("sol") returns null.

Upvotes: 1

Tom O.
Tom O.

Reputation: 5941

function getUserChoice() {
  var user_sol = document.getElementById("sol").value;
  console.log(user_sol);
}
<div class="form-group">
  <input id="sol" class="input-sol form-control" placeholder="Enter number" type="text" required>
  <button class="btn btn-warning btn-large" id="submit" type="button" onClick="getUserChoice()">Get Images</button>
</div>

As mentioned in the comments, your problem is that you have an invalid ID attribute. You can only have 1 ID per element and it must be unique. Read this: https://www.w3schools.com/tags/att_global_id.asp

As you can see, you code works by simply fixing the ID attribute.

Upvotes: 2

Quentin
Quentin

Reputation: 943220

The class attribute accepts a list of space-separated class names. Classes are designed to represent groups, and elements can be members of multiple groups.

An id is a unique identifier, like a social security number. An element can only have one, and no element can share that of another.

focusedInput and appendedInput sound more like classes than ids. Move them to the class attribute.

Upvotes: 0

Related Questions