2

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>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Leakcim
  • 73
  • 2
  • 8

2 Answers2

6

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>
Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • 1
    I would go with `btn.disabled = !this.value;` and by default set `disabled` property on the DOM instead of setting it in JS otherwise – Adrien Martinet Aug 13 '19 at 12:28
  • @AdrienMartinet I agree on setting disabled in the DOM. Updated. The logical check I chose to keep close to the OP, but your way would also work just fine. – Jamiec Aug 13 '19 at 12:31
  • It's worth including a call to [`String.prototype.trim()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim), otherwise a string of white-space can be submitted (I realise that this isn't a stated requirement though). – David Thomas Aug 13 '19 at 12:37
  • Thank you for your help. @Jamiec I do not understand this part: btn.disabled = (this.value === ''); Disabled is not boolean? I do not understand why it is assigned the value this.value === '' – Leakcim Aug 13 '19 at 12:54
  • Yes Disable is a boolean attribute https://www.w3schools.com/tags/att_disabled.asp :) – Adrien Martinet Aug 13 '19 at 12:54
  • That's why you can shorten the assignment to `btn.disabled = !this.value;` or `btn.disabled = !this.value.trim();` – Adrien Martinet Aug 13 '19 at 12:56
2

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.

jcubic
  • 61,973
  • 54
  • 229
  • 402