Check if input value is empty and display an alert

前端 未结 4 714
猫巷女王i
猫巷女王i 2020-12-24 14:15

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?

         


        
相关标签:
4条回答
  • 2020-12-24 14:21

    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;
            }
        });
     });
    
    0 讨论(0)
  • 2020-12-24 14:37

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

    0 讨论(0)
  • 2020-12-24 14:40

    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"); 
               }
         });
    });
    
    0 讨论(0)
  • 2020-12-24 14:43
    $('#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');
       }
    });
    
    0 讨论(0)
提交回复
热议问题