0

I have a simple form:

<form name ="Add" action="Add-Results.php" method="post">
 <label for="name" class="smallfont">Name</label>
 <input type="text" name="name" size="30" />
 <label for="name_error" class="error">Please enter a name</label>
 <input type="image" name="submit" src="../Content/Images/login-submit.gif">
</form>

Which works fine until I add in the following jquery

$(document).ready(function()
{
 $(".error").hide();
 $("input[name=submit]").click(function() 
 {
  $(".error").hide();
  var name = $("input[name=name]").val();

  if (name == "") $("label[for=name_error]").show();

 return false;
 });

});
</script>

When I put in the jquery nothing happens when I click the submit. When I take out the jquery the form posts without a problem. Any ideas?

3 Answers 3

4
if (name == "") $("label[for=name_error]").show();

Should be

if (name == ""){ $("label[for=name_error]").show(); return false}
Sign up to request clarification or add additional context in comments.

3 Comments

@ Mike Muta: To explain the reason for this change, return false will cancel the POST of the form so in your example the onclick method you add always cancel the submit. By wraping the show and return fals inside the if statement you will only cancel submit if you display the error message.
and remove the return false; that is already there and now is always returned and therefore prevents the form to submit.
Yup sorry for the lack of explanation but ditto everything @David said
2

Form will not be sent, becuase you used return false at the end of click handler - so you prevent default action to run. And submitting form is a default action made on click - and it won't be run. Try removing that line.

Comments

0

Maybe you could put all the logic in a function, and on the onclick event of the button call that function, like this:

function checkName() { var flag = true;

$(".error").hide();
var name = $("input[name=name]").val();

if (name == "")
{
    $("label[for=name_error]").show();
    flag = false;
}

return flag;

}

then

<input type="image" name="submit" onClick="checkName()" src="../Content/Images/login-submit.gif">

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.