如何提醒用户空白表单域

How to alert user for blank form fields?

本文关键字:表单 空白 用户 何提醒      更新时间:2023-09-26

我有这个表单,它有 3 个输入,当用户将字段留空时,会弹出一个对话框,提醒用户字段为空。 我在下面的代码仅适用于 2 个特定输入。 当我尝试向代码添加另一个输入时,它不起作用。 它仅适用于 2 个输入。 如何使其适用于所有三个?

<script type="text/javascript">
function val(){
    var missingFields = false;
    var strFields = "";
    var mileage=document.getElementById("mile").value;
    var location=document.getElementById("loc").value;


    if(mileage=='' || isNaN(mileage))
    {
    missingFields = true;
    strFields += "     Your Google Map's mileage'n";
    }
   if(location=='' )
    {
    missingFields = true;
    strFields += "     Your business name'n";
    }


    if( missingFields ) {
        alert( "I'm sorry, but you must provide the following field(s) before continuing:'n" + strFields );
        return false;
    }
    return true;
}
</script>

显示 3 个警报可能会令人不安,请使用如下内容:

$(document).on('submit', 'form', function () {
    var empty = $(this).find('input[type=text]').filter(function() {
        return $.trim(this.value) === "";
    });
    if(empty.length) {
        alert('Please fill in all the fields');
        return false;
    }
});

灵感来自这篇文章。

或者,您可以使用 HTML 数据属性以这种方式对每个字段进行验证:

<form data-alert="You must provide:" action="" method="post">
    <input type="text" id="one" data-alert="Your Google Map's mileage" />
    <input type="text" id="two" data-alert="Your business name" />
    <input type="submit" value="Submit" />
</form>

。结合 jQuery:

$('form').on('submit', function () {
    var thisForm = $(this);
    var thisAlert = thisForm.data('alert');
    var canSubmit = true;
    thisForm.find('input[type=text]').each(function(i) {
        var thisInput = $(this);
        if ( !$.trim(thisInput.val()) ) {
            thisAlert += ''n' + thisInput.data('alert');
            canSubmit = false;
        };
    });
    if( !canSubmit ) {
        alert( thisAlert );
        return false;
    }
});

看看这个脚本的实际效果。

当然,您只能选择/检查具有属性data-alert的输入元素(这意味着它们是必需的)。混合输入元素的示例。

您可以在输入字段中添加所需的标签。不需要jQuery。

<input required type="text" name="name"/>

试试这个

var fields = ["a", "b", "c"]; // "a" is your "mile"
var empties= [];
for(var i=0; i<fields.length; i++)
{
    if(!$('#'+fields[i]).val().trim())
        empties.push(fields[i]);
}
if(empties.length)
{
    alert('you must enter the following fields '+empties.join(', '));
    return false;
}
else
    return true;

而不是这个

var name = $('#mile').val();
if (!name.trim()) {
    alert('you must enter in your mile');
    return false;
}