[javascript] Check if input value is empty and display an alert

How is it possible to display an alert with jQuery if I click the submit button and the value of the input field is empty?

<input type="text" id="myMessage" name="shoutbox_msg" size="16" class="field_nosize" maxlength="150">&nbsp;
<input id="submit" type="submit" name="submit_post" class="button_nosize" value="Senden" onclick="sendMessage(); clearInput();">

This question is related to javascript html jquery forms validation

The answer is


Check empty input with removing space(if user enter space) from input using trim

$(document).ready(function(){     
       $('#button').click(function(){
            if($.trim($('#fname').val()) == '')
           {
               $('#fname').css("border-color", "red");
               alert("Empty"); 
           }
     });
});

Better one is here.

$('#submit').click(function()
{
    if( !$('#myMessage').val() ) {
       alert('warning');
    }
});

And you don't necessarily need .length or see if its >0 since an empty string evaluates to false anyway but if you'd like to for readability purposes:

$('#submit').on('click',function()
{
    if( $('#myMessage').val().length === 0 ) {
        alert('warning');
    }
});

If you're sure it will always operate on a textfield element then you can just use this.value.

$('#submit').click(function()
{
      if( !document.getElementById('myMessage').value ) {
          alert('warning');
      }
});

Also you should take note that $('input:text') grabs multiple elements, specify a context or use the this keyword if you just want a reference to a lone element ( provided theres one textfield in the context's descendants/children ).


Also you can try this, if you want to focus on same text after error.

If you wants to show this error message in a paragraph then you can use this one:

 $(document).ready(function () {
    $("#submit").click(function () {
        if($('#selBooks').val() === '') {
            $("#Paragraph_id").text("Please select a book and then proceed.").show();
            $('#selBooks').focus();
            return false;
        }
    });
 });

You could create a function that checks every input in an input class like below

 function validateForm() {
  
    var anyFieldIsEmpty = jQuery(".myclass").filter(function () {
        return $.trim(this.value).length === 0;
    }).length > 0

    if (anyFieldIsEmpty) {
        alert("Fill all the necessary fields");
        var empty = $(".myclass").filter(function () {
            return $.trim(this.value).length === 0;
        })
        empty.css("border", "1px solid red");
        return false;
    } else {
        return true;
    }
}

What this does is it checks every input in 'myclass' and if empty it gives alert and colour the border of the input and user will recognize which input is not filled.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to forms

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

Examples related to validation

Rails 2.3.4 Persisting Model on Validation Failure Input type number "only numeric value" validation How can I manually set an Angular form field as invalid? Laravel Password & Password_Confirmation Validation Reactjs - Form input validation Get all validation errors from Angular 2 FormGroup Min / Max Validator in Angular 2 Final How to validate white spaces/empty spaces? [Angular 2] How to Validate on Max File Size in Laravel? WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery