[英]Make alert appear when start typing input
我試圖使某些事情僅在用戶將數據輸入到已創建的輸入元素中時發生。 但是,我不想驗證是否已輸入數據,也不希望用戶按下按鈕來檢查是否已輸入數據,我希望在輸入字段中輸入第一個數據值后立即進行操作。 我決定只使用一個我想創建的類似東西的演示來消除混亂:
我努力了:
var input = document.getElementById("input"); if(input == ""){ alert("no value"); }else{ input.style.background = "blue"; }
<input type="text" id="input">
但是似乎沒有任何作用。 由於什么原因它不起作用? 因此,在此示例中,我只希望在輸入第一個數據值時背景為藍色。我也嘗試過:
var input = document.getElementById("input");
if(input.length == 0){
alert("no value");
}else{
input.style.background = "blue";
}
和:
var input = document.getElementById("input");
if(input == undefined){
alert("no value");
}else{
input.style.background = "blue";
}
以及使用!=
和!==
變體
我想念的東西很小嗎?
您正在檢查實際元素,而不是它的價值。 而且,您沒有為該元素設置任何事件偵聽器。 但是,在輸入值之后不檢查任何值在邏輯上沒有多大意義。
// When data is inputted into the element, trigger a callback function document.getElementById("input").addEventListener("input", function(){ // Check the value of the element if(input.value == ""){ alert("no value"); }else{ input.style.background = "blue"; } });
<input type="text" id="input">
嘗試這個,
jQuery的
$('#input').keyup(()=>{
if($('#input').val() == ""){
alert("no value");
} else{
$('#input').css({backgroundColor: 'your-color'});
}
});
function handleCurrentInput(event) { const value = event.target.value; if (!value) { alert("no value"); } else { alert("value entered -->", value); } }
<input type="text" id="input" onInput="handleCurrentInput(event)">
你好你可以試試看
<input type="text" id="input" onkeyup="inputfun()">
<script type="text/javascript">
function inputfun(){
var input = document.getElementById("input");
if(input.value == ""){
input.style.background = "";
alert("no value");
}else{
input.style.background = "blue";
}
}
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.