Home > Software engineering >  How to add the adjacentHTML text only once onblur
How to add the adjacentHTML text only once onblur

Time:09-17

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(); 
       }
}

The P tag gets created multiple times

CodePudding user response:

You can simply check the existence of the p tag before adding it

    if(!document.getElementById("sp_billing_first_name_field")){  
         n1.insertAdjacentHTML('afterend', '<p class="sp-error-notice" id="sp_billing_first_name_field"></p>');     
    }

CodePudding user response:

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't remove() it in else condition. Also there is no need to put n == '' in the condition your first condition is enough and satisfies n == ''.

Here what I did is to check whether the element was created if that already exists it returns which causes repetition.

function myFunction() { 
  // for name
let n = document.getElementById("billing_first_name").value;  
// let name_text;
if(document.getElementById("billing_first_name").nextSibling.nodeName == 'P'){
return
}
  if ( n.length < 3 ) {
    var n1 = document.getElementById('billing_first_name'); 
    n1.insertAdjacentHTML('afterend', '<p class="sp-error-notice" id="sp_billing_first_name_field">Error.</p>');     
  }
}
myFunction()
myFunction()
myFunction()

function myFunction2() {
if(document.getElementById('sp_billing_first_name_field')){
  document.getElementById('sp_billing_first_name_field').style.display = 'none'
  }
}
<input type="text" id="billing_first_name" onclick='myFunction2()'>

  • Related