Click here to Skip to main content
15,890,995 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Doesn't work when I click submit.

                $(document).ready(function(){
                $("#submit-button").click(function(e){

		        var firstName = $("#first-name").val();
                var name_regex = /^[a-zA-Z]+$/;
        if(firstName.length == 0){
			$("#p1").text("*Field must be filled!*");
			$("#first-name").focus();
		}

		else if(!firstName.match(name_regex) || firstName.length == 0 ){
			$("#p1").text("Please use alphabets only.");
			$("#first-name").focus();
		}
	});
});
<input id="submit-button" type="submit" name="submit" value="Submit">

What I have tried:

I've tried to use /-----/i regex instead of /------/. 
I've tried to use alert instead of $("p").text();
I've checked my script src link.
Posted
Updated 17-May-18 5:11am
v3
Comments
Richard MacCutchan 17-May-18 10:53am    
What does "doesn't work" mean?
Member 13504137 17-May-18 10:59am    
If I input number in name field I expect a message to pop under input field when I click on Submit button. I expect that because it doesn't fit the regex I've wrote.

1 solution

Your code is working, but the page is being submitted before the message can be shown.

You need to call e.preventDefault() if your validation fails:
JavaScript
$(function(){
    $("#submit-button").click(function(e){
        var firstName = $("#first-name").val();
        if (firstName.length === 0){
            $("#p1").text("*Field must be filled!*");
            $("#first-name").focus();
            e.preventDefault();
            return;
        }

        if (!firstName.match(/^[a-zA-Z]+$/)){
            $("#p1").text("Please use alphabets only.");
            $("#first-name").focus();
            e.preventDefault();
            return;
        }
    });
});

You might be better off looking at the jQuery Validation Plugin[^] instead.
 
Share this answer
 
Comments
Member 13504137 17-May-18 11:18am    
That worked.. :) thanks a lot! Im gonna read more about preventDefault() and jQuery Validation Plugin as you said.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900