JavaScript表单验证未显示警报或更改输入背景颜色

时间:2016-04-09 12:14:21

标签: javascript html

我制作了这个脚本来验证我的表单但是,当我留下文本字段时,没有任何反应,输入框或警告消息没有红色背景,正如我预期的那样。

function validateForm()
{
/* For all forms in the document */
for(var i in document.forms)
{
    /* Get the forms inputs */
    var inputs = document.forms[i].getElementsByTagName("input");

    for(var j in inputs)
    {
        /* Make sure we don't try to validate the submit button */
        if(inputs[j].type == "text")
        {
            if(inputs[j].value.trim() == "" || inputs[j].value.trim() == null)
            {
                inputs[j].style.backgroundColor = "red";
                alert("Please ensure all boxes are filled in");
                return false;
            }
        }
    }
}
}

如果有帮助,这是我的一个表格:

<form name="searchArtists" method="get" onsubmit="return validateForm()">
    <input type="text" name="artists" placeholder="Search Artists" maxlength="255" size="32" />
    <input type="submit" name="submit" value="Search"/>
</form>

3 个答案:

答案 0 :(得分:2)

对占位符文本使用占位符属性

<input type="text" name="artists" placeholder="Search Artists"...

我建议另一个问题是不允许使用空格

if(inputs[j].value.trim() == "") { ...

答案 1 :(得分:0)

在您的代码i中有一个表单,j是一个输入。因此,document.forms[i]inputs[j]无法正常工作。

修正了JavaScript函数:

function validateForm()
{
    /* For all forms in the document */
    for(var i in document.forms)
    {
        /* Get the forms inputs */
        var inputs = i.getElementsByTagName("input");

        for(var j in inputs)
        {
            /* Make sure we don't try to validate the submit button */
            /* Trim value to not allow values with only spaces */
            if(j.type == "text")
            {
                if(j.value == null || j.value.trim() == "")
                {
                    j.style.backgroundColor = "red";
                    alert("Please ensure all boxes are filled in");
                    return false;
                }
            }
        }
    }
}

HTML:

<form name="searchArtists" method="get" onsubmit="return validateForm()">
    <input type="text" name="artists" placeholder="Search Artists" maxlength="255" size="32" />
    <button type="submit">Search</button>
</form>

答案 2 :(得分:0)

让我们稍微减少一点,首先在我们要验证的元素上添加一个ID,我还建议您更改当前的&#34;值&#34;到一个&#34;占位符&#34;,就像这样:

<input id="artistQueryInput" type="text" name="artists" placeholder="Search Artists" maxlength="255" size="32" />

现在开始使用Javascript:

function validateForm(){
    //Get element
    var inputElement = document.getElementById('artistQueryInput');

    //Get value
    var rawArtistQueryString = inputElement.value;

    //Strip all whitespace
    var baseArtistQueryString = rawArtistQueryString.replace(/ /g, "");

    //Validate string without whitespace
    if((baseArtistQueryString == '') || (baseArtistQueryString == NULL) ||){
         //Assuming j is artistQueryInput
         inputElement.style.backgroundColor = "red";
         alert("Please ensure all boxes are filled in");
         return false;
    }
}