javascript - 输入不为空时显示按钮 | 不工作的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>
解决方案
为了在 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>
推荐阅读
- ios - iOS“开发人员”角色可以创建/上传 Testflight 版本吗?
- html - 如何阻止文本在 HTML 输入框中居中?
- c# - 如何以列表形式将 Linq 添加到 EF 数据到 Class Object C#?
- python - auzre databricks 安装应用程序,但无法从 databricks 笔记本输入命令
- python - 排序顺序搜索
- eval - Python - 存储函数定义以供以后使用
- visual-studio - 在 VS2019 中使用 GTK+ 时 ffiw64.c 中的读取访问冲突
- spring - 手动配置 Spring Boot Reactive Mongo
- android - google hangouts meet 的包名是什么?
- php - 无法访问属性 - Laravel