簡體   English   中英

如何確保輸入不為空?

[英]How to make sure input is not empty?

我正在為練習構建一個PhoneGap應用程序,這意味着我希望不惜一切代價避免jQuery,不接受任何參數。 我有一個帶有工作按鈕的輸入類型,但是如果用戶刪除所有保留空白輸入字段的數字,然后按加號或減號按鈕,它將在輸入框“ Nan”中報告。 如何將其設置為“ 0”?

 window.onload = function() { var CapsNum = localStorage.getItem("CapsNum"); if (CapsNum == null) { setCapsNum = "0"; } else { document.getElementById("caps").value = CapsNum; } } window.onbeforeunload = function() { localStorage.setItem("CapsNum", document.getElementById("caps").value); } function PlusCaps() { var nextValue = parseInt(document.getElementById("caps").value) + 1; console.log(nextValue); setNextValue(nextValue); } function MinusCaps() { var nextValue = parseInt(document.getElementById("caps").value) - 1; // If the next value is valid... if (nextValue >=0) { // Set the next value. setNextValue(nextValue); } } function setNextValue(nextValue) { localStorage.setItem("CapsNum", nextValue); document.getElementById("caps").value = nextValue; } function isNumberKey(evt) { var charCode = (evt.which) ? evt.which : event.keyCode; if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) return false; return true; } 
 .button { font-size: 18px; display: inline-block; width: 50px; height: 50px; margin-top: 10px; margin-bottom: 10px; line-height: 20px; vertical-align: top; outline: none; cursor: pointer; border: 1px solid rgba(80, 80, 80, 1); -moz-border-radius: 8px; -webkit-border-radius: 3px; border-radius: 4px; } #caps { margin-top:12px; margin-bottom: 12px; font-size: 35px; width: 60px; text-align: center; background: TRANSPARENT; color: YELLOW; border: 2px solid; outline: none; } 
 <div id="CapsButton" tabindex="1"> <input type="button" id="minus" class="button" value="-" style="margin-right:10px" onclick="MinusCaps()" /> <input type="tel" id="caps" maxlength="3" size="3" pattern="[0-9]+" value="" autocomplete="off" onkeypress="return isNumberKey(event)" /> <input type="button" id="plus" class="button" value="+" style="margin-left:10px" onclick="PlusCaps()" /></div> 

您可以使用isNaN()。 如果該值等於NaN,則此函數返回true。 否則返回false。 例如:

if(isNaN(document.getElementById("caps").value)){
   document.getElementById("caps").value = 0;
}

已編輯
問題是document.getElementById(“ caps”)。value返回空字符串,並且parceInt(“”)= NaN所以您可以使用:

function ifInputEmpty(){
  if(document.getElementById("caps").value === ""){
     return 0;
  } else {
     return parseInt(document.getElementById("caps").value);
  }
}

前加帽

function PlusCaps() {
  var prevVal = ifInputEmpty();
  var nextValue = prevVal + 1;
  console.log(nextValue);
  setNextValue(nextValue);
}

暫無
暫無

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

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