Using jQuery to prevent form submission when input fields are empty

后端 未结 5 824
没有蜡笔的小新
没有蜡笔的小新 2020-12-14 08:38

The solution should be pretty straightforward. I\'m trying to prevent the form from submitting properly when no value is found within the input boxes. Here\'s my JSFiddle: h

相关标签:
5条回答
  • 2020-12-14 09:14

    Two things, #1 the check for empty fields should happen on every attempt of submit, #2 you need to check each field individually

    $('#form').submit(function() {
        if ($.trim($("#email").val()) === "" || $.trim($("#user_name").val()) === "") {
            alert('you did not fill out one of the fields');
            return false;
        }
    });
    

    Updated fiddle

    0 讨论(0)
  • 2020-12-14 09:16

    Your check occurs on page load. You need to check the field when the form is submitted.

    $('#form').submit(function(e) {
        if ($.trim($("#email, #user_name").val()) === "") {
            e.preventDefault();
            alert('you did not fill out one of the fields');
        }
    });
    
    0 讨论(0)
  • 2020-12-14 09:17

    I guess that this will help:

    $('#form').submit(function(e) {
        e.preventDefault();
        $("#email, #user_name").each(function(){
            if($.trim(this.value) == ""){
                alert('you did not fill out one of the fields');
            } else {
                // Submit 
            }
        })
    })
    
    0 讨论(0)
  • 2020-12-14 09:24

    Put your if statement inside the callback:

    $('#form').submit(function(e) {
        if ($.trim($("#email").val()) === "" || $.trim($("#user_name").val())) {
            e.preventDefault();
            alert('you did not fill out one of the fields');
            //You can return false here as well
        }
    });
    
    0 讨论(0)
  • 2020-12-14 09:37

    HTML5: use required in input tag

    • A boolean attribute.

    • Input field must be filled out before submitting the form.

    • Works with text, search, url, tel, email, password, date pickers, number, checkbox, radio, and file.

      <input required type='text'...>
      

    w3schools hint

    0 讨论(0)
提交回复
热议问题