简体   繁体   中英

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>

That happened because the "submit" action refresh the page what means the browser console will be reloaded and all the logs will be cleared.

If you want to stop this behavior to see your log message you could use preventDefault() or return false; like:

_form.addEventListener('submit', (e)=>{
     e.preventDefault();
     console.log(_title);

     //Or
     //return false;
});

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>

you have to prevent the default action that get's triggerred ( which is replacing/reloading the page with something else ) on type=submit , and explicitly submit the form with form.submit() maybe after a few seconds depending on your needs;

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

_form.addEventListener('submit', evt => {
    evt.preventDefault();
    console.log(_title);
});

After submit, the page is redirecting to same page(in absence of href or action) or different so you are not able to see the console output

As per my knowledge , have found 2 approaches to deal with the issue

  1. call preventDefault on the event which will stop redirecting and you see console output

code snippet

index.html

<a class="clear-tasks btn black" href="some url">Clear Tasks</a>

app.js

const clearBtn = document.querySelector(".clear-tasks");
clearBtn.addEventListener('click',function(e){
    e.preventDefault();
    console.log(e);
});
  1. Keep href="#"

code snippet

index.html

<a class="clear-tasks btn black" href="#">Clear Tasks</a>

app.js

const clearBtn = document.querySelector(".clear-tasks");
clearBtn.addEventListener('click',(e)=>{
    console.log(e);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM