Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();">
like image 271
The Masta Avatar asked Sep 16 '13 09:09

The Masta


3 Answers

$('#submit').click(function(){
   if($('#myMessage').val() == ''){
      alert('Input can not be left blank');
   }
});

Update

If you don't want whitespace also u can remove them using jQuery.trim()

Description: Remove the whitespace from the beginning and end of a string.

$('#submit').click(function(){
   if($.trim($('#myMessage').val()) == ''){
      alert('Input can not be left blank');
   }
});
like image 182
Tushar Gupta - curioustushar Avatar answered Nov 12 '22 13:11

Tushar Gupta - curioustushar


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 ).

like image 32
Zigri2612 Avatar answered Nov 12 '22 13:11

Zigri2612


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;
        }
    });
 });
like image 3
Shiv Yadav Avatar answered Nov 12 '22 12:11

Shiv Yadav