I am trying to validate my woocommerce chekout form on the frontend only with javascript. The valdation executes correctly but the problem is that the function gets called everytime I remove the focus from the input field (I have used onblur event).
The div gets created multiple times. I want to have it displayed only one time else it should be removed. Can anyone suggest a solution??
Attaching the code and SS below.
<h3>my custom heading</h3>
<p class="form-row form-row validate-required">
<input type="billing_first_name">... </p>
<p class="sp-error-notice" id="sp_billing_first_name_field"> </p>
function myFunction() {
// for name
let n = document.getElementById("billing_first_name").value;
// let name_text;
if ( n.length < 3 || n == '' ) {
var n1 = document.getElementById('billing_first_name');
n1.insertAdjacentHTML('afterend', '<p class="sp-error-notice" id="sp_billing_first_name_field">This is a test.</p>');
}
else {
var n1 = document.getElementById("sp_billing_first_name_field");
n1.remove();
}
}
2
Answers
You can simply check the existence of the p tag before adding it
There is no need to put
else
, because the element<p class="sp-error-notice" id="sp_billing_first_name_field">This is a test.</p>
was never created it can’tremove()
it in else condition. Also there is no need to putn == ''
in the condition your first condition is enough and satisfiesn == ''
.Here what I did is to check whether the element was created if that already exists it returns which causes repetition.