I want to add an event listener to a form to display the form’s fields in a paragraph, without jQuery.
The text should show up in the paragraph demoJS
but it doesn’t. However, when I use console.log
, the excepted resuslts appear in the console.
Here’s my code:
function afficher_etudiant() {
document.getElementById("demoJS").innerHTML +=
document.getElementById("nom").value + "<br>" +
document.getElementById("prenom").value + "<br>" +
document.getElementById("num_etu").value + "<br>" +
document.getElementById("cursus").value + "<br>";
console.log(document.getElementById("demoJS").innerHTML);
}
var bouton = document.getElementById("formulaireJS");
bouton.addEventListener("onclick", afficher_etudiant);
bouton.addEventListener("onsubmit", afficher_etudiant);
bouton.addEventListener("submit", afficher_etudiant);
<p id="demoJS"> </p>
<form id="formulaireJS">
Nom:<br>
<input type="text" name="nom" id="nom" required>
<br> Prénom:
<br>
<input type="text" name="prenom" id="prenom" required>
<br> Numero étudiant:<br>
<input type="text" name="num_etu" id="num_etu" required>
<br>
<select name="cursus" id="cursus" form="formulaireJS">
<option value="math">math</option>
<option value="info">info</option>
<option value="cmi">CMI</option>
</select>
<br>
<br>
<br>
<br>
<input type="submit" value="Ajouter" class="boutonSoumission">
</form>
答案 0 :(得分:1)
Several problems here.
function afficher_etudiant() {
document.getElementById("demoJS").innerHTML =
document.getElementById("nom").value + "<br>" +
document.getElementById("prenom").value + "<br>" +
document.getElementById("num_etu").value + "<br>" +
document.getElementById("cursus").value + "<br>";
}
var theForm = document.getElementById("formulaireJS");
theForm.addEventListener("change", afficher_etudiant);
// this is redundant, but I'll include it for completeness:
var bouton = document.getElementsByClassName("boutonSoumission")[0];
bouton.addEventListener("click", afficher_etudiant);
<p id="demoJS"> </p>
<form id="formulaireJS">
Nom:<br>
<input type="text" name="nom" id="nom" required>
<br> Prénom:
<br>
<input type="text" name="prenom" id="prenom" required>
<br> Numero étudiant:<br>
<input type="text" name="num_etu" id="num_etu" required>
<br>
<select name="cursus" id="cursus" form="formulaireJS">
<option value="math">math</option>
<option value="info">info</option>
<option value="cmi">CMI</option>
</select>
<br>
<input type="button" value="Ajouter" class="boutonSoumission">
</form>
答案 1 :(得分:1)
您可以通过两种方式修复代码:
直接调用该函数并删除事件侦听器
<input type="button" onclick="afficher_etudiant()" value="Ajouter" class="boutonSoumission" >
如果您想使用事件监听器,那么:
<input type="button" value="Ajouter" class="boutonSoumission" id="myButton" > // for the button code
var bouton = document.getElementById("myButton") ; // In Script
bouton.addEventListener("click",afficher_etudiant);
将类型添加为&#34;按钮&#34;并为按钮添加ID
只需保持点击&#39;事件监听器并删除其他人。同时获取按钮的ID而不是表单。