0

I created a form with several inputs, one of them is "Full Name",and of course a submit button at the end.

function checks if the name input is alphabetical characters only, if true, it will append the div element , add the css class, snackbar will fade in and out, and finally disappear. what is wrong with the following code:

$(document).ready(function(){
$(".submitForm").click(function(){
    var fullname = $("#firstName").value; 
    var checkIfTrue = /^[A-Za-z ]+$/.test(fullname);
    if (checkIfTrue==true) {
        $('body').append("<div id='textBox'> some text</div>"); 
        $("#textBox").addClass("showPopup");
        setTimeout(function(){
            $("#textBox").remove();}, 3000); 
        return true;
    } 
    else {
        alert("wrong input");
        return false;
    }   
})
})

and there is the relevant css:

.showPopup {
  visibility : visible;
  animation : fadein 0.5s, fadeout 0.5s 2.5s;
}

@keyframes fadein {
  from {bottom: 0; opacity: 0;}
  to {bottom: 20px; opacity: 1;}
}

@keyframes fadeout {
  from {bottom: 20px; opacity: 1;}
  to {bottom: 0; opacity: 0;}
}

cheers (couldn't figure it out myself with : jQuery: append() object, remove() it with delay() )

1 Answer 1

0

There is some minor issues like the use of .value (vanilla JS) instead of .val() (jQuery)...

And certainly the major issue, the submit prevention on button click. See .preventDefault().

For the rest, see comments within code:

$(document).ready(function(){
  $(".submitForm").click(function(event){
    event.preventDefault();  // Prevent the submit behavior of the button

    var fullname = $("#firstName").val(); // .val() instead of .value
    var checkIfTrue = /^[A-Za-z ]+$/.test(fullname);
    if (checkIfTrue) {  // No need for the ==true
      $('body').append("<div id='textBox'> some text</div>"); 
      $("#textBox").addClass("showPopup");
      setTimeout(function(){
        $("#textBox").remove();
        $(this).closest("form").submit();  // Since it's ok and the animation's over... Submit the form.
      }, 3000); 
      //return true;  // No need to return anything from an event handler
    } 
    else {
      alert("wrong input");
      //return false;  // No need to return anything from an event handler
    }   
  })
})
Sign up to request clarification or add additional context in comments.

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.