0

I've got this code here:

 <input type="text" class="todo-input" placeholder="Gebe hier dein Taskein">
 <button onclick="task = document.getElementsByClassName('todo-input').value; 
 window.alert(task)">Hinzufügen</button>

But why do I geht undefined and not the text in the input field? And what do I have to do that I get the input text?

Donald
  • 7
  • 5
  • 1
    Does this answer your question? [What do querySelectorAll and getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return) – evolutionxbox Jun 04 '21 at 13:21

3 Answers3

1

document.getElementsByClassName returns an array of elements.

To get the value you want to retrieve the element by index, e.g:

task = document.getElementsByClassName('todo-input')[0].value;

Also, you should consider using an ID instead of a class. IDs are meant to be unique, classes are not. e.g.

<input type="text" id="myInput" class="todo-input" placeholder="Gebe hier dein Taskein">
task = document.getElementById('myInput').value;
FauxBlue
  • 24
  • 1
  • 3
0

Because you are selecting by class name, you must define the element number of which you want to select, since JavaScript returns a collection of elements otherwise. In your current code, JavaScript is unable to determine with element with a class name of "todo-input" to select, so it'll always return undefined.

Since the input box is the only element on the page with the "todo-input" class, you can use the modified code below in order to select the specific element and get its value. Remember, counting starts at 0 in JavaScript, so this code will select the first input on the page that has the specified class name.

    <input type="text" class="todo-input" placeholder="Gebe hier dein Taskein">
 <button onclick="task = document.getElementsByClassName('todo-input')[0].value; 
 window.alert(task)">Hinzufügen</button>

As seen in the modified code above, the selector is now paired with [0], which will effectivly select the textbox on the page and display it's value.

document.getElementsByClassName('todo-input')[0].value

If your page will contain additional elements with the same class name or you add a new element with the same class before the current element, make sure to adjust the number value so you're selecting the right element.

Austin
  • 97
  • 1
  • 6
0

Please check the following link. https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName

getElementsByClassName returns the array-like object not object.

<input type="text" class="todo-input" placeholder="Gebe hier dein Taskein">
<button onclick="task = document.getElementsByClassName('todo-input')[0].value; 
 window.alert(task)">Hinzufügen</button>
Reinis
  • 477
  • 1
  • 5
  • 13