JS检查是否存在值

问题描述:

由于某种原因,我的JS没有按照我的想法反应。 提交按钮在页面加载时被禁用。JS检查是否存在值

当在数据字段中输入值时,类应该改变并且应该启用提交按钮。两者都没有发生。

这似乎是一个标准的代码,但仍然是一个问题?

window.onload = function() { 
 
    document.getElementById('form_submit').disabled = true; 
 
} 
 

 
function validate() { 
 
    if (document.getElementById('datum').value == false) { 
 
    document.getElementById('div_datum').className = "col-md-2 input-group has-warning"; 
 
    } else { 
 
    document.getElementById('div_datum').className = "col-md-2 input-group has-success"; 
 
    document.getElementById('form_submit').disabled = false; 
 
    } 
 
}
<div class="container"> 
 
    <div class="form-group row"> 
 
    <label for="datum" class="col-md-2 form-label">Datum toolbox</label> 
 
    <div class="col-md-2 input-group has-warning" id="div_datum"> 
 
     <input type="text" class="form-control datepicker" id="datum" name="datum" onkeyup="validate()" onclick="validate()"><span class="input-group-addon"><span class="glyphicon glyphicon-remove" aria-hidden="true" data-toggle="tooltip" title="Verplicht veld"></span></span> 
 
    </div> 
 
    </div> 
 
    <button type="submit" class="btn btn-primary" id="form_submit">Verstuur</button> 
 

 
</div>

+0

我已将您的代码块转换为Stack Snippet。当我在字段中输入时,它会启用按钮。你能澄清问题是什么吗? –

+1

你怎么隐藏按钮?您的示例中没有任何内容隐藏或显示按钮。 –

这条线:

if (document.getElementById('datum').value == false) 

将分支到附连的if块的一对夫妇值(例如,如果I型0,而不仅仅是当该值空白(因为"0" == false是奇怪的,true)。更可靠的空白值检查是:

if (!document.getElementById('datum').value) 

只有在value""时才会分支。 (您可能会或可能不会,如果你想清除开头和结尾的空格要添加到.trim()value。)

另外,我不禁注意到,你的validate功能不落disabledtrue,只有false。如果我输入一些内容,然后回退它呢?您可能想要再次禁用该按钮。所以:

function validate() { 
    if (document.getElementById('datum').value == false) { 
    document.getElementById('div_datum').className = "col-md-2 input-group has-warning"; 
    document.getElementById('form_submit').disabled = true; 
    } else { 
    document.getElementById('div_datum').className = "col-md-2 input-group has-success"; 
    document.getElementById('form_submit').disabled = false; 
    } 
} 

或更多的重构:

function validate() { 
    var invalid = !document.getElementById('datum').value.trim(); 
    document.getElementById('div_datum').className = "col-md-2 input-group " + (invalid ? "has-warning" : "has-success"); 
    document.getElementById('form_submit').disabled = invalid; 
} 

注意String.prototype.trim中加入ES 5.1(2011年6月),因此它不会在过时的浏览器IE8一样存在,虽然它可以是多填充的;请参阅polyfill的链接。