Jquery 获取所有空输入,并将每个输入存储在唯一变量中

Jquery 获取所有空输入,并将每个输入存储在唯一变量中,jquery,forms,event-handling,Jquery,Forms,Event Handling,我有一个包含多个输入的表单,在发送之前,我会检查是否有任何输入为空: <input type="text" name="number" id="number" style="float:left;clear:both;"/> <input type="text" name="road" id="road" style="float:left;clear:both;" /> <input type="text" name="town" id="

我有一个包含多个输入的表单,在发送之前,我会检查是否有任何输入为空:

    <input type="text" name="number" id="number" style="float:left;clear:both;"/>
    <input type="text" name="road" id="road" style="float:left;clear:both;" />
    <input type="text" name="town" id="town" style="float:left;clear:both;" />
    <input type="submit" name="submit" value="submit" id="submit" />
我想在错误框中准确地显示哪些字段是空的(带有一条用户友好的消息),但我不确定如何在不加载if()语句的情况下最有效地显示这些字段

逻辑大致如下:

  • 检查是否有任何字段为空
  • 如果“town”为空,则将“town”存储在变量中,如果“road”为空。。等
  • 将错误框中的文本更改为类似“并非所有字段都已完成,请填写$town和$road…”
  • 您可以使用以下代码:

    function submitForm() {
        var empty = $('form input[value=""]');
        if (empty.length > 0) {
            $('#error-box').show();
            empty.each(function (index, element) {
                $('#error-box p').text($('#error-box p').text() + $(this).attr('name') + ' ');
            });
            $('#error-box p').text($('#error-box p').text() + 'fields are not filled');
        } else {
            // complete your submit
        }
    }
    
    我建议您在尝试推出自己的自定义解决方案之前,先试用该插件。
    function submitForm() {
        var empty = $('form input[value=""]');
        if (empty.length > 0) {
            $('#error-box').show();
            empty.each(function (index, element) {
                $('#error-box p').text($('#error-box p').text() + $(this).attr('name') + ' ');
            });
            $('#error-box p').text($('#error-box p').text() + 'fields are not filled');
        } else {
            // complete your submit
        }
    }