0

I need to do an email input and button, and if it is valid to open a successful registration pop-up with adding style to it, but if the email input is empty or invalid to open an error pop-up. I don't know why, but the If, Else statement doesn't work and when I press the button nothing happens

Here is my code input code in HTML

<input name="email" class="form-control" type="email" placeholder="Enter your email" required>
<button type="button" class="btn btn_100 3x" >Register</button>


<script>
var testEmail = /^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
if (testEmail.test(valueToTest))
 {
  $(document).ready(function(){
  $(".3x").click(function(){
  $(".3X").css("display", "block");
  });}); 
 }
else
 {
  $(document).ready(function(){
  $(".3x").click(function(){
  $(".2rr").css("display", "block");
  });});
 }
</script>
Sadeed_pv
  • 513
  • 1
  • 9
  • 22
Fors1t
  • 73
  • 1
  • 7

1 Answers1

2

There are many problems with your code, consider using only once $(document).ready and $(".3x").click(function(){.

On a side note, not sure what elements are these: $(".3X"), $(".2rr") but since classnames start with a number, CSS cannot be applied to them (unless you escape the number, see this: https://stackoverflow.com/a/45293575/5334486)

$(document).ready(function() {

  const testEmail = /^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;

  $(".3x").click(function() {
    const valueToTest = $('input[type="email"]').val()

    if (testEmail.test(valueToTest)) {
      console.log("Email is valid.");
      $(".3X").css("display", "block");
    } else {
      console.log("Email IS NOT valid.");
      $(".2rr").css("display", "block");
    }
  })

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="email" class="form-control" type="email" placeholder="Enter your email" required>

<button type="button" class="btn btn_100 3x">Register</button>
GrafiCode
  • 3,307
  • 3
  • 26
  • 31
  • the $(".3X"), $(".2rr") are the div class of the pop-ups, sorry that I didn't put it here, but they are big and I don't know if I need to – Fors1t Sep 11 '22 at 12:05
  • It worked, Thank you :), I have 1 question, why do I need to use $(document).ready only once? – Fors1t Sep 11 '22 at 12:14
  • `$(document).ready` is fired when all page elements have been added to the DOM, and they are ready to be accessed / manipulated. If you wrap all your code inside this function, it will be executed when document is ready, no need to declare it multiple times. – GrafiCode Sep 11 '22 at 14:04