admin管理员组

文章数量:1302334

I would like the "Send" button to be disabled if the input is empty. I want to manage this in the JavaScript file. I know that it is possible in HTML to call a function on the input but I prefer to use an event in the js file.

//javascript
let inputElt = document.getElementById('input');
let btn = document.getElementById('button');

if (inputElt.value !== '') {
  btn.disabled = false;
} else {
  btn.disabled = true;
}
<input placeholder="Enter some text" name="name" id='input' />
<button id='button'>Réserver</button>

I would like the "Send" button to be disabled if the input is empty. I want to manage this in the JavaScript file. I know that it is possible in HTML to call a function on the input but I prefer to use an event in the js file.

https://codepen.io/leakcim-web/pen/gOYPpqo

//javascript
let inputElt = document.getElementById('input');
let btn = document.getElementById('button');

if (inputElt.value !== '') {
  btn.disabled = false;
} else {
  btn.disabled = true;
}
<input placeholder="Enter some text" name="name" id='input' />
<button id='button'>Réserver</button>

Share edited Aug 14, 2019 at 11:33 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Aug 13, 2019 at 12:14 LeakcimLeakcim 731 gold badge3 silver badges8 bronze badges 4
  • 1 use input event – Pranav C Balan Commented Aug 13, 2019 at 12:14
  • use addEventListener in your js to your inputElt, and update the btn disabled from the listener... – user11855261 Commented Aug 13, 2019 at 12:17
  • I had a similar problem and this question / answer helped me a lot. Thank you. – Axle Max Commented Dec 30, 2020 at 4:05
  • I posted my probelm and solution here if it helps anyone stackoverflow./questions/65501771/… – Axle Max Commented Dec 30, 2020 at 4:05
Add a ment  | 

2 Answers 2

Reset to default 7

You can use addEventListener to add an event to the textbox and enable/disable as appropriate

let inputElt = document.getElementById('input');
let btn = document.getElementById('button');

inputElt.addEventListener("input", function(){
  btn.disabled = (this.value === '');
})
<input placeholder="Enter some text" name="name" id='input'/>
<button id='button' disabled>Réserver</button>

Just as amusement, you can do this in just CSS and html, reference Matching an empty input box using CSS

#input:invalid + button {
    opacity: 0.5;
    pointer-events: none;
}
<input placeholder="Enter some text" name="name" id='input' required="required"/>
<button id='button'>Réserver</button>

And if you have something in between the button and input you can use #input ~ #button. also you don't need the id attributes you can use type="submit" on button then use input ~ [type="submit"] then it will work with any input at the same nesting.

本文标签: javascriptDisable a button if empty inputStack Overflow