Invalid left hand assignment error in console

Viewed 48

I am getting this error in console.

Uncaught ReferenceError: Invalid left-hand side in assignment
    at changeFirstDate (script.js:156)
    at HTMLInputElement.oninput (index.html:97)

I double checked my codes and I can't find the problem

here is the HTML:

   <p>Type First Date </p>
          <input id="typefirstdate" type="text" placeholder="(example: June 1 2018)" oninput="changeFirstDate()">

   <p id="firstDate"></p> 

and here is the JS :

document.getElementById('typefirstdate').addEventListener('input', changeFirstDate);

    function changeFirstDate() {
        let firstDate = document.getElementById('typefirstdate').value;
      document.getElementById('firstDate') = firstDate;
    }

I have read other questions similar to my problem but there seems no answer to this type of questions.

2 Answers

change the function to this:

function changeFirstDate() {
      let firstDate = document.getElementById('typefirstdate').value;
      document.getElementById('firstDate').innerHTML = firstDate;
}

The more general answer is :

You cannot do something.getElementById(id) = somethingElse

The element on the left side of the "=" cannot be affected a value because it's the anonymous result of a function execution (getElementById). Thus the error "Invalid left-hand side in assignment".

You have to use a function (accessor or other) that specifically lets you overwrite the content of the element. That's why .innerHtml was suggested.

Related