Check if input value is empty and display an alert

前端 未结 4 720
猫巷女王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: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 ).

提交回复
热议问题