首页 > 解决方案 > 输入不为空时显示按钮 | 不工作的JS

问题描述

我想要一个带有“Go!”文本的按钮 当用户输入内容时显示在我的 html 输入旁边。如果输入为空,则不得看到按钮。我正在使用 Javascript 尝试执行此操作,但它似乎不起作用,我做错了什么?

var b = document.getElementById('button');

var input = document.getElementById("inputtext");
if(input.value === ""){
 alert("Input a value to continue");
 b.style.display = "none";
}else{
 b.style.display = "inline-block";
}
<input type="text" id="inputtext" placeholder="Enter name">
<button id="button">GO!
</button>

标签: javascripthtmlinput

解决方案


为了在 JS 中进行这项工作,您可以将输入侦听器用作:

var b = document.getElementById('button');
var input = document.getElementById("inputtext");
b.style.display = "none";

if(input.value === ""){
 alert("Input a value to continue");
}
 
input.addEventListener('input', function() {

if(input.value === ""){
 alert("Input a value to continue");
 b.style.display = "none";
}
else{

  b.style.display = "inline-block";
 }
});
<input type="text" id="inputtext" placeholder="Enter name">
<button id="button">GO!
</button>

使用 CSS 的另一个解决方案是:-

#inputtext:placeholder-shown ~ button{
 display:none;
}
<input type="text" id="inputtext" placeholder="Enter name">
<button id="button">GO!
</button>


推荐阅读