When I’m trying my page, when I fill my form it instantly reload and nothing happen, I can see the glimse of an error in the console but it disapears instantly…
I have been trying to modify my form but nothing seems to work
// je gere la generation de nombre
function donneAlea(){
nombre = Math.floor(Math.random()*6+1)
return nombre
}
// je gere la banque
function management(somme,pari,victoire){
if(victoire){
somme = somme + pari
}
else{
somme -= pari
}
return somme
}
// je m'ocuppe du bouton
let pression = document.getElementById('presse');
pression.onclick = function(){
let baliseNom =getElementById('lenom');
let nom = baliseNom.value
let body = document.querySelector('body')
body.innerHTML(`<p>test ${nom}</p>`)
}
console.log("test")
<!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>Veux tu parier tout ton argent</title>
<script src = "script.js" defer></script>
</head>
<body>
<header>
<h1>La chance souris aux audacieux</h1>
<p> Tu ne gagnes rien si tu restes sur le côté</p>
</header>
<main>
<h2>Tu peux d'abord commencer par remplir es informations</h2>
<form id ='formulaire'>
<label for = "lenom" >Entrer votre nom</label>
<input id = 'lenom' type = "text" name ='lenom'>
<button id='presse'>envoyer</button>
</form>
</main>
</body>
</html>
2
Answers
The main problem, which is causing the ‘glimpse’ of the error in the console, is that the button click submits the parent form. This in turn reloads the page, as you didn’t supply a
action
attribute on that form. To fix this, hook to thesubmit
event of theform
element (not theclick
of thebutton
) and callpreventDefault()
on the event that’s raised viaaddEventListener()
.Secondly, and this is likely the cause of the error you could see momentarily, you’re missing the
document.
prefix on the call togetElementById('lenom')
.Lastly,
innerHTML
is a property, not a method, so you don’t call it with parentheses containing an argument – you simply set its value.Here’s working example with those changes made:
My answer is not different from the one above but just some additions. As explained earlier you are missing a preventDefault to prevent default action and document keyword on the getElementById.
Here my changes
And my javascript code is this
By explicitly setting type="submit", you make it clear that the button is intended to submit the form. This improves code readability and maintainability.