1

I am using .after() like below for Form Validation

$("#contactNum").after(
    '<span class="invalid-feedback">Please fill up this Field.</span>'
);

I would like to check if this span is present or absent to avoid add this span twice.

2 Answers 2

1

You can check if the next element after your contactNum doesn't have particular class i.e invalid-feedback using this add your span tag.

Demo Code :

//using class
if (!$("#contactNum").next().hasClass("invalid-feedback")) {
  $("#contactNum").after(
    '<span class="invalid-feedback">Please fill up this Field.</span>'
  );
}
/*
//using text
if ($("#contactNum").next().text().trim() != "Please fill up this Field.".trim()) {
  $("#contactNum").after(
    '<span class="invalid-feedback">Please fill up this Field.</span>'
  );
}*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="contactNum">
<span class="invalid-feedback">Please fill up this Field.</span>

Sign up to request clarification or add additional context in comments.

Comments

0

You can simply just check the next span length using next and length and if already have span you can just fill up text otherwise you can insertAfter check below code.

if( !$('#contactNum').next('span.invalid-feedback').length ){
    $('<span class="invalid-feedback">Please fill up this Field.</span>').insertAfter($('#contactNum'));
}else{
    $('#contactNum').next('span.invalid-feedback').text('Please fill up this Field.');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="contactNum">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.