When you access any element of the DOM, it is usual to save it in a variable. This is something that at first might seem very simple, but if you are a beginner programmer it might give you some headaches sometimes.
To begin with, let's see how you can get an element from the DOM using JavaScript. First we are going to define an example input field:
<input id=planet">
Now let's see how we can get the value of the field:
const planet = document.querySelector('input#planet').value;
However, this variable will not be updated when the DOM changes. That is to say, if for example you want to send the value you have stored to your server through a dynamic form, you will have to get the element from the DOM again.
The car variable gets its value from the state that the DOM had at the time the browser executed the statement through which we get the value of the field, and unless we do not update its value, it will not change.
Let's imagine that you want to send the value of the field through an AJAX form:
const planet = document.querySelector('input#planet').value;
document.querySelector('form').addEventListener('submit', event => {
// Code that sends the variable to the server
});
It is very common for a beginner programmer to do this, the value of the #planet field may have changed when we send the planet variable, which will not have been updated. the solution is to get the value just before sending it to the server:
document.querySelector('form').addEventListener('submit', event => {
const planet = document.querySelector('input#planet').value;
// Code that sends the variable to the server
});
In case you want the code inside the event to be not so long, you can store a reference to the field, which is different from its value:
const inputCoche= document.querySelector('input#planet');
document.querySelector('form').addEventListener('submit', event => {
const planet = inputCoche.value;
// Código que envía la la variable planet al servidor
});