BlackRoseGoat
BlackRoseGoat

Reputation: 25

Jquery Validation and Messages

I'm trying to get an error message to show when my fields are missing input. Once both are filled in I want a success message to show in place of #error. Not sure why I'm not getting any message currently.

$("input[type='button']").click(function() {
  $("form").validate({
    rules: {
      username: "required"
    },
    messages: {
      username: "please enter a name"
    }
  });
  alert("Submitted");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/jquery.validate.min.js"></script>
<form>
  <p>
    <label for="username">Username:</label>
    <input type="text" name="username" id="username">
  </p>

  <p>
    <label for="pw">Password:</label>
    <input type="password" name="pw" id="pw">
  </p>

  <p>
    <input type="button" value="Submit">
  </p>

  <!-- placeholder for response if form data is correct/incorrect -->
  <p id="error"></p>
</form>

Upvotes: 1

Views: 51

Answers (1)

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33933

What about this ?

$("input[type='button']").click(function() {

    if($("#username").val()==""){
        $("#error").html("Please enter a name");
        return;
    }
    if($("#pw").val()==""){
        $("#error").html("Password required");
        return;
    }
    alert("Submitted");
});

Upvotes: 1

Related Questions