我如何检测我的提交按钮是用javascript点击的



大家好
因此,基本上我必须编写一个使用javascript计算一定金额的网站代码,以下是该网站的示例:请在此处查看
所以基本上客户用数量填写表格,我必须显示他的命令总数,他不需要提交表格

不完整的代码是这样的:

<h1>Vente de Pizza</h1>
<form method="post" action="#">
Nom du client<input type="text" name="nom" /> <br> <BR></BR>
adresse<input type="text" name="adresse" /><br>
<h1>Produits à acheter</h1>
<table border = "1">
<tr><th>Nom du produit</th>
<th>Prix unitaire</th>
<th>Quantité</th>
</tr>
<tr>
<td>Pizza 4 fromages</td>
<td>80</td>
<td><input type="text" name="QTE1" id = "x1" /></td>
</tr>
<tr>
<td>Pizza Herbo</td>
<td>75</td>
<td><input type="text" name="QTE2" id = "x2"/></td>
</tr>
<tr>
<td>Pizza viande hachée</td>
<td>100</td>
<td><input type="text" name="QTE3" id = "x3"/></td>
</tr>
<tr>
<td>Pizza Fruit de mer</td>
<td>120</td>
<td><input type="text" name="QTE4" id = "x4"/></td>
</tr>
</table>
<p font = "bold" style="font-weight: BOLD;"> Paiment par: </p><br>
<input type="radio" name="banque" id="">Carte bancaire
<input type="radio" name="banque" id="">Chèque <BR></BR>
Numéro de la carte bancaire<input type="text" name="numCB" id = "x5" style="width: 400px;"/> <br><BR>
<button class="btn" type="submit"  onkeydown = "mySubmit()" id ="bouton">Envoyer</button> <BR></BR>
<script>
function TotalCalculate(){
var x1 = document.getElementById("x1").value;
var x2 = document.getElementById("x2").value;
var x3 = document.getElementById("x3").value;
var x4 = document.getElementById("x4").value;
var tot = x1*80;
document.getElementById("Total").addEventListener("click", writeTotal);
function writeTotal(){
document.getElementById("Total").write(tot);
}
}
</script>
Merci de votre visite le montant total de votre commande est : 
<input type="text" name="Total" onclick="TotalCalculate()" id = "Total"/> 
</form>

正如你所看到的,我从用户那里得到了价值,并计算了要支付的总额,但它没有显示任何内容。我需要添加一个listner,但我找不到如何添加一个写东西的listner。请帮助

您想要的事件是changeinput。例如

document.querySelectorAll("input, select, textarea").forEach(function(input) {
input.addEventListener('input', TotalCalculate)
})
function TotalCalculate() {

var x1 = document.getElementById("x1").value;
var x2 = document.getElementById("x2").value;
var x3 = document.getElementById("x3").value;
var x4 = document.getElementById("x4").value;
var tot1 = x1 * 80;
var tot2 = x2 * 75;   // <-- fixed these
var tot3 = x3 * 100;   // <-- fixed these
var tot4 = x4 * 120;   // <-- fixed these
var tot = tot1 + tot2 + tot3 + tot4;
// document.write("tot");
document.getElementById("Total").value = tot;
}
<form method="post" action="#" onsubmit="TotalCalculate(); return false">
<input type="text" id="x1"><br>
<input type="text" id="x2"><br>
<input type="text" id="x3"><br>
<input type="text" id="x4"><br>
<input type="submit">
</form>
<br>
total: <input id="Total">

Coucou,

如果你有jQuery加载的,你可以使用这个

$('#bouton').on('click', function(e){ 
e.preventDefault();
alert('clicked');
});

或者如果它只是纯JS:

var button = document.getElementById('button')
button.onclick = function () {
console.log('Click just happened')
}

最新更新