Home > other >  Can't save DOM element .value property to a variable
Can't save DOM element .value property to a variable

Time:12-30

I'm trying to create a simple Javascript program that adds/removes items to an array, then displays the array by DOM manipulation.

I've created a reference called 'input', that is supposed to be the value of the HTML text input field. It's supposed to look like this:

let input = document.getElementById("text").value;

When I try to identify that variable in the console, it recognizes it as undefined. But, if I reference the variable like this:

let input = document.getElementById("text");

and call, input.value, it shows the appropriate value. For ex: "Lorem ipsum". What am I doing wrong?

I've provided a codepen link to see the output.

HTML

    <div>
        <form>
          <input type ="text" id="text">
          <button onClick="updateList(input.value)" type ="button">Add</button>
          <button onClick = "reset()" type="button">Clear</button>
        </form>
      </div>
      <div id='para'>
       <!--list goes here-->
      </div>

Javascript

//input.value will be used
let input = document.getElementById("text");
let groceryList = ["Grapes", "Juice", "Apples"];

//Div where output will be placed
let para = document.getElementById('para');

//Creation of ul
let unorderedList = document.createElement('ul');
para.appendChild(unorderedList);

//Creates list on DOM
const createList = groceryList.forEach((grocery) => 
    {
        //Creation of list item
        let li = document.createElement('li');
        li.innerText = grocery; // For instance, just to give us something to see
        li.className = "grocery-item";
        unorderedList.appendChild(li);
    });

//Resets para
const reset = () => {
    para.removeChild();
}


//Adds item
const updateList = (item) => {
    reset();
    groceryList.push(item);
    return createList;
}

CodePudding user response:

If you use let input = document.getElementById("text").value; you assign the initial value of your input field which is undefined at start to your variable. This value will never change.

If you use let input = document.getElementById("text"); you set a reference to the input field to your variable and you can then retrieve the current value of this element by using input.value

I hope that my answer will be understandable because my English is really poor.

  • Related