Reputation: 69
I want a button with the text 'Go!' to display next to my html input when a user types something in. If the input is empty the button must not be seen. I am using Javascript to try and do this but it doesn't seem to be working, what am I doing wrong?
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>
Upvotes: 0
Views: 1067
Reputation: 548
See the code below. You need to listen for a change event or a keydown event to fire the function.
var b = document.getElementById('button');
var input = document.getElementById("inputtext");
input.addEventListener("input", displayButton); // Event to listen for a change
function displayButton() {
if(input.value === ""){
alert("Input a value to continue"); // Remove this because it's bad user experience, use console.log if it's for testing.
//b.style.display = "none"; // Disable the button for accessibility instead of hidding
b.disabled = true;
}else{
//b.style.display = "inline-block";
b.disabled = false;
}
}
displayButton(); // Run the code at load time
<input type="text" id="inputtext" placeholder="Enter name">
<button id="button">GO!
</button>
Upvotes: 1
Reputation: 897
For making this work in JS you can use the input listener as :
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>
Anothe solution using CSS is:-
#inputtext:placeholder-shown ~ button{
display:none;
}
<input type="text" id="inputtext" placeholder="Enter name">
<button id="button">GO!
</button>
Upvotes: 1