Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

41
Views
I am trying to use an user HTML input to change a javascript object value

I am trying to use HTML 'input' to change apiData.id value. I'm new to javascript and not sure if this is correct. Any suggestions would be greatly appreciated.

const apiData = {
    url: 'https://pokeapi.co/api/v2/',
    type: 'pokemon',
    id: '76',
}

const input = document.getElementById('container');
const newId = apiData.id;

function eventController(event) {
    newId = event.target.value;
}
input.addEventListener('change', eventController, false);
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pokemon</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div id="container">
        <input id="input">
        <input type="submit" value="Catch">
    </div>




    <div class="pokemon"></div>
    <script src="main.js"></script>
</body>

</html>

7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

newId is const, so you cannot assign it with a new value after it has been declared.

But even if you could (and you can, by making it a variable), that would not affect apiData.id, as newId is assigned with the value of apiData.id, but they are not bound together.

You should just assign apiData.id directly with a new value:

const apiData = {
    url: 'https://pokeapi.co/api/v2/',
    type: 'pokemon',
    id: '76',
}

const input = document.getElementById('container');
// const newId = apiData.id;

function eventController(event) {
    apiData.id = event.target.value;
}
input.addEventListener('change', eventController, false);
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pokemon</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div id="container">
        <input id="input">
        <input type="submit" value="Catch">
    </div>




    <div class="pokemon"></div>
    <script src="main.js"></script>
</body>

</html>

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs