JS-Dev-101 practice question 9 of 25

A developer creates a simple webpage with an input field. When a user enters text and clicks the button, the actual value must be displayed in the…

Full set: 148 questions
A developer creates a simple webpage with an input field. When a user enters text and clicks the button, the actual value must be displayed in the console: HTML: JavaScript: 01 const button = document.querySelector('button'); 02 button.addEventListener('click', () => { 03 const input = document.querySelector('input'); 04 console.log(input.getAttribute('value')); 05 }); When the user clicks the button, the output is always "Hello". What needs to be done to make this code work as expected?
Answer options
A: Replace line 02 with button.addCallback("click", function() {
B: Replace line 03 with const input = document.getElementByIdName('input');
C: Replace line 04 with console.log(input.value); Correct answer
D: Replace line 02 with button.addEventListener("onclick", function() {
Correct Answer:
C. Replace line 04 with console.log(input.value);
Explanation

The getAttribute('value') method retrieves the value of the HTML value attribute as it was defined in the initial page source. It does not reflect the live, current text a user has typed into the input field. To get the current value of an input element, you must use the .value property of the DOM element object. This property always holds the up-to-date content of the form control.

Why Incorrect

A. addCallback is not a standard DOM method for event handling; the correct method is addEventListener.
B. getElementByIdName is not a valid DOM method. Methods like getElementById or getElementsByName exist, but not this one.
D. The event type for addEventListener is "click". "onclick" is the name of the HTML attribute or object property, not the event type string.

References

1. MDN Web Docs, HTMLInputElement.value. "The value property of the HTMLInputElement interface gets or sets the current value of the element."

2. MDN Web Docs, Element.getAttribute(). "It is recommended that you use element.value to get the current value of a text input, because the value attribute does not dynamically update as the user types."

3. W3C, HTML Living Standard, Section 4.10.5.1.10 "The value attribute". "The value IDL attribute must reflect the current value of the element."

Scroll to Top