I have a check when sending a form with an error message via alert. Tell me, please, how instead of alert output this message in the block with the class .error-msg ?

 $("#EasyNewsletterSubscriptionForm").submit(function(event) { $('#EasyNewsletterSubscriptionSubmit').click(); event.preventDefault(); }); $('#EasyNewsletterSubscriptionSubmit').on('click', function() { var email_validate = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/; if ((document.getElementById("YourName").value == 0) || (document.getElementById("YourEmail").value.length == 0)) { alert("<?php echo $EasyNewsletterSubscription_Error1; ?>") } else if (!document.getElementById("YourEmail").value.match(email_validate)) { alert("<?php echo $EasyNewsletterSubscription_Error2; ?>") } else { $.ajax({ url: 'index.php?route=module/easynewslettersubscription/subscribecustomer', type: 'post', data: $('#EasyNewsletterSubscriptionForm').serialize(), success: function(response) { $('#EasyNewsletterSubscriptionSuccess').html("<div class='alert alert-success ens_success' style='display: none;'>" + response + "</div>"); $('.ens_success').fadeIn('slow'); $('#YourName').val(''); $('#YourEmail').val(''); } }); } }); 
 <div class="list-group"> <div class="error-msg"> </div> <form id="EasyNewsletterSubscriptionForm"> <div id="EasyNewsletterSubscriptionSuccess"></div> <input type="text" name="YourName" id="YourName" class="form-control" placeholder="Your Name" value="" /> <br /> <input type="text" name="YourEmail" id="YourEmail" class="form-control" placeholder="Your Email" value="" /> <br /> <a id="EasyNewsletterSubscriptionSubmit" class="btn btn-default"> <?php echo $EasyNewsletterSubscription_SubscribeNow; ?> </a> </form> </div> 

    2 answers 2

    Instead of alert

     $('.error-msg').html('<?php echo $EasyNewsletterSubscription_Error1; ?>') 
    • as noted 1111100000 - if there is no block, then this case will fall with the error ".html () not a function" since $ ('. error-msg) will be empty - alexoander

    Make sure that such a block is already present when it is called:

     function showError (msg = '') { let element = document.querySelector('.error-msg') if(element) { element.innerHTML(`<span>${msg}</span>`) element.classList.add('shown') } }