0

. Here is my code. I am trying to validate email,but nothing is happening when clicking on validate button. Please reply. It's not showing message and i don't know why it is not showing. It is not a complicated code :

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>




    function validateEmail(email) {
  var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return re.test(email);
}

function validate() {

  $("#result").text("");
  var email = $("#email").val();
  if (validateEmail(email)) {
    $("#result").text(email + " is valid :)");
    $("#result").css("color", "green");
  } else {
    $("#result").text(email + " is not valid :(");
    $("#result").css("color", "red");
  }
  return false;
}


$("#validate").bind("click", validate);

    </script>


</head>





 <form>
  <p>Enter an email address:</p>
  <input id='email'>
  <button type='submit' id='validate' >Validate!</button>
</form>

<h2 id='result'></h2>
10
  • You should probably bind validateEmail, since there is no validate Commented Dec 18, 2017 at 6:50
  • sorry ,but then also it wont work Commented Dec 18, 2017 at 6:52
  • Also open developers console and check errors there Commented Dec 18, 2017 at 6:53
  • how open console> Commented Dec 18, 2017 at 6:53
  • 1
    How can I debug my JavaScript code? stackoverflow.com/questions/988363/… @user7441072 Commented Dec 18, 2017 at 6:56

1 Answer 1

2

Try putting your script tag at the bottom of your body, or putting your bind code in the onLoad hook.

The way your code is structured at the moment, your bind code runs before the elements in the body are loaded, ie it binds to elements that don't exist. The reason it works for other people is probably because the load order is browser-dependant. So if re-ordering your code still doesn't work, it would be interesting to know what browser you are using.

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

1 Comment

a working example of the above answer jsfiddle.net/o2gxgz9r/20344

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.