Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

console.log doesn't work inside event submit

I can't do a console.log. Outside the event listener it works flawless. But when I want to do a console.log within a event listener (form submit) nothing appears in the console.

<form id="formMovies">
    <input type="text" id="title">
    <button type="submit" id="boton">Guardar</button>
</form>

<script>
var _form = document.querySelector("#formMovies");
var _title = document.querySelector("#title").value;

_form.addEventListener('submit', ()=>{
    console.log(_title);
});
</script>
like image 331
n21b Avatar asked Feb 06 '26 04:02

n21b


1 Answers

The issue is when the code runs before clicking the button, there is no value set to _title. Take the value inside the event handler function. You can also use event.preventDefault() to prevent the submission of the form and you can see the output.

<form id="formMovies">
    <input type="text" id="title">
    <button type="submit" id="boton">Guardar</button>
</form>

<script>
var _form = document.querySelector("#formMovies");

_form.addEventListener('submit', (e)=>{
  var _title = document.querySelector("#title").value;
  console.log(_title);
  e.preventDefault();
});
</script>
like image 73
Mamun Avatar answered Feb 07 '26 19:02

Mamun