0

I am attempting to get a value from an HTML element but it is pulling back a blank.

Input information: vendorNumber: 123456 documentNumber: 123456

Results: Search {vendorNumber: "", documentNumber: ""}

Desired results: Search {vendorNumber: "123456", documentNumber: "123456"}

Please see my script below:

class Search {
    constructor(vendorNumber, documentNumber) {
        this.vendorNumber = vendorNumber;
        this.documentNumber = documentNumber;
    }
}

const vendorNumber = document.getElementById('vendorNumber').value,
    documentNumber = document.getElementById('documentNumber').value,
    submit = document.getElementById('myBtn'),
    newSearch = new Search(vendorNumber, documentNumber);

if (submit) {
    submit.addEventListener('click', onClick);
}

function onClick(){
    console.log(newSearch);
    event.preventDefault()
}
  • Does this answer your question? [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Anurag Srivastava Apr 01 '20 at 15:02
  • 1
    Can you provide a complete example in a code snippet to demonstrate the problem? As a *guess* it looks like you're fetching the input values before the user has had a chance to input anything. – David Apr 01 '20 at 15:05
  • 2
    By the moment of defining `vendorNumber` and `documentNumber` their values are probably empty if you dont set them earlier in the document. You need to assign values to them right when you want the function to be called, in your case `onclick` event. – Adrian Solarczyk Apr 01 '20 at 15:15

1 Answers1

0

The value returns blank because it would only get the input values when you trigger an event. Put the vendorNumber, documentNumber, and newSearch variables inside onClick function.

jstarnate
  • 319
  • 3
  • 15