TRS7
TRS7

Reputation: 149

Display Message only upon validation using jQuery

I am trying to make a message appear on the viewport only once all text areas are filled. Right now myMessage appears immediately upon clicking the button on my page even though the first name field has yet to be validated. How do I make the myMessage ONLY appear once the form element for "First Name" is filled out by the user?

$(document).ready(function() {
  $("#submitinfo").click(function() {
    var myFirstName = $("#first_name").val().trim();
    if (!myFirstName) {
      $("#first_error").html("You must Enter a First Name");
      $('#first_name').focus();
    } else {
      $("#first_error").html("");
    }
    $("#message").css('background-color', 'red');
    var myMessage = "Your name is " + myFirstName;
    $("#message").html(myMessage);
    return false;
  });

});
<label for="first_name">First Name:</label>
<input type="text" id="first_name" name="first_name"> <span class="error" id="first_error"></span>
<input type="button" id="submitinfo" value="Submit">
<span class="message" id="message"></span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

Upvotes: 0

Views: 42

Answers (2)

Sanchit Patiyal
Sanchit Patiyal

Reputation: 4920

Currently, you are displaying message whenever user clicks the button instead of that display only when user enters something in input field by moving the message block in else part like this

$(document).ready(function() {
  $("#submitinfo").click(function() {
    var myFirstName = $("#first_name").val().trim();
    if (!myFirstName) {
      $("#first_error").html("You must Enter a First Name");
      $('#first_name').focus();
      $("#message").html("");
    } else {
      $("#first_error").html("");
    $("#message").css('background-color', 'red');
    var myMessage = "Your name is " + myFirstName;
    $("#message").html(myMessage);
    }
    
    return false;
  });

});
<label for="first_name">First Name:</label>
<input type="text" id="first_name" name="first_name"> <span class="error" id="first_error"></span>
<input type="button" id="submitinfo" value="Submit">
<span class="message" id="message"></span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

Upvotes: 1

Flynamic
Flynamic

Reputation: 98

Put your myMessage code inside the else block. You'd also want to remove the content of #message if !myFirstName is true.

Upvotes: 1

Related Questions