skip to Main Content

The problem I am having is that I cannot change elements of a variable.

I have tried many different ways, but I am struggling to take a input from HTML and changing a JS variable.

What I am making will include a random character generator in the future so changing parts of the variable is key if this is the correct way of doing it.

I have been using variables like this in Javascript:

let Player = {
  name: "Alex", 
  age: 20,
  Height: 190,
};

The problem I am having is that I cannot change elements of the variable. They way I have been trying is this:

document.getElementById("PlayerNameInput").innerHTML = Player.name

Any alternatives and/or better ways to get the same result? Changing the variable properties multiple times is a needed part.

2

Answers


  1. Read the value property of an input element and change the property of the object to its value.

    If you set the name of the input identical to a property in the object things will be very smooth:

    In your html:

    <body>
      <input placeholder="First name" type="text" name="firstName"><br>
      <input placeholder="Last name" type="text" name="lastName"><br>
      <input placeholder="Hobby" type="text" name="hobby">
      <script src="changeObjFromInput.js"></script>
    </body>
    

    In your script changeObjFromInputjs:

    let person = {
      firstName: '',
      lastName: '',
      hobby: ''
    }
    
    document.addEventListener('keyup', e => {
      let input = e.target.closest('input');
      if (!input) { return; }
      person[input.name] = input.value;
      console.log(person);
    });
    

    Edit:
    Or did you mean the other way around, from object to input fields, we can do that too, value is both readable and writeable:

    let person = {
      firstName: 'John',
      lastName: 'Doe',
      hobby: 'fishing'
    }
    
    for (let key in person) {
      document.querySelector(`input[name=${key}]`).value = person[key];
    }
    
    document.addEventListener('keyup', e => {
      let input = e.target.closest('input');
      if (!input) { return; }
      person[input.name] = input.value;
      console.log(person);
    });
    
    Login or Signup to reply.
  2. Maybe what you mean is like this. code innerHTML is used for set elements eg .innerHTML = "<div>New Elm</div>"

    let Player = {
      name: "Alex", 
      age: 20,
      Height: 190,
    };
    
    // get value from `html`
    Player.name = document.getElementById("PlayerNameInput").value
    // set new value to `html`
    document.getElementById("PlayerNameInput").value = Player.name
    console.log(Player)
    <input id="PlayerNameInput" value="John">
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search