簡體   English   中英

JS檢查值是否存在

[英]JS check if value exists

由於某種原因,我的JS沒有按照我的預期做出反應。 頁面加載時,提交按鈕被禁用。

在基准字段中輸入en值后,該類應更改,並且應該啟用提交按鈕。 都沒有發生。

似乎是標准代碼,但還是有問題?

 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> 

這行:

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

將在幾個值上分支到if塊(例如,如果我鍵入0,而不僅僅是在值是空的時候(因為"0" == false ,奇怪的是, true )。值是:

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

僅當value""該分支才會分支。 (如果要清除.trim()和結尾的空白,則可能會或可能不想在value上添加.trim() 。)

另外,我不禁要注意,您的validate函數從不會將disabled設置為true ,而只能將false設置為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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM