简体   繁体   English

如何使用 addEventListener 设置条件

[英]how to put a condition with an addEventListener

hello I have an order form.你好,我有一个订单。 I would like to be able to display an error message if total_qty=0如果 total_qty=0,我希望能够显示错误消息

When the user clicks on validate the order当用户点击验证订单时

<!DOCTYPE html>
<html>
<body>

<button id="btn">validate the order</button>
<span id="total_qte"></span> 
<script>
var btn = document.querySelector('#commander);
var total=document.getElementById('total_qty').innerHTML ;

// addEventListener 
btn.addEventListener('click', function(){

if (var total== 0){
         var p = document.createElement('p');
 p.innerText = 'error order;
 document.body.appendChild(p); }

});
</script>

</body>
</html>
<!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>Document</title>
</head>
<body>
    
    <input id="quantity" value="0" type="number">
    <button id="btn">validate the order</button>
    <div id="errorMessage"></div>

    <script>
        const btn = document.querySelector('#btn');

        // addEventListener 
        btn.addEventListener('click', function(){
            const total = parseFloat(document.getElementById('quantity').value);
            console.log("total: ", total);

            if ( total === 0){                    
                const p = document.getElementById('errorMessage');
                p.innerText = 'error order';
            }
            else{
                const p = document.getElementById('errorMessage');
                p.innerText = "";
            }
        });

    </script>

  
</body>
</html>
        <script>
 var btn = document.querySelector('#commander');


// addEventListener 
btn.addEventListener('click', function(){
 var total=document.getElementById('total_qte').innerHTML ;
  console.log('TOTAL',total);
   if ( total== '0' || parseFloat(total)==0){ // tu avais un espace entre la quote et le zéro..
       //alert("Aucun article sélectionner ou votre commande a déjà été envoyée" );
          var p = document.createElement('p');
      p.innerText = 'Votre commande a déjà été envoyée';
      document.body.appendChild(p);
    } 
});
        </script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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