最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Check If User Input Is Empty - Stack Overflow

programmeradmin1浏览0评论

I'm having some trouble checking whether the input field is empty and when it is I want to revert it to the content in the h1 tag.

<body>
    <h1>Enter Your Username</h1>
    <input type="text" id="username" />
  </body>

const input = document.querySelector("input");
const h1 = document.querySelector("h1");

input.addEventListener("input", (e) => {
  h1.innerText = `Wele ${input.value}`;
});

if (input.length === 0) {
  h1.innerText = "Enter Your Username";
}

I'm having some trouble checking whether the input field is empty and when it is I want to revert it to the content in the h1 tag.

<body>
    <h1>Enter Your Username</h1>
    <input type="text" id="username" />
  </body>

const input = document.querySelector("input");
const h1 = document.querySelector("h1");

input.addEventListener("input", (e) => {
  h1.innerText = `Wele ${input.value}`;
});

if (input.length === 0) {
  h1.innerText = "Enter Your Username";
}
Share Improve this question edited Feb 18, 2023 at 22:47 Agrim Singh 5393 silver badges18 bronze badges asked Mar 24, 2021 at 17:39 Elli RaynaiElli Raynai 211 silver badge2 bronze badges 3
  • Wele to StackOverflow! Please read How do I ask a good question? and How to create a Minimal, Reproducible Example – Rojo Commented Mar 24, 2021 at 17:42
  • Use always textContent instead of innerText – Roko C. Buljan Commented Mar 24, 2021 at 17:49
  • Instead of checking the value via JavaScript you could also simply add the required attribute to the input element. – Carsten Massmann Commented Feb 18, 2023 at 7:43
Add a ment  | 

3 Answers 3

Reset to default 3

input has not length property. You probably meant:

if (input.value.length === 0) {
  h1.innerText = "Enter Your Username";
}

or without whitespaces: (thanks to Roko)

if (input.value.trim().length === 0) {
      h1.innerText = "Enter Your Username";
    }

Currently the input length check is not inside the event handler. Ideally you want to check if the input is empty every time the input value changes. So you want it inside your input.addEventListener callback

input.addEventListener("input", function(e) {
  h1.innerText = this.value.length === 0 ?
    "Enter Your Username" :
    `Wele ${input.value}`; 
});
**HTML**
<body>
    <h1>Enter Your Username</h1> 
    <input type="text" id="username">
</body>

**JS** 
let inputEl = document.querySelector('input') 

let h1 = document.querySelector('h1') 
inputEl.addEventListener('input',()=>{ 
  h1.innerText = "Wele, " + inputEl.value 
 if (inputEl.value.length === 0) h1.innerText = "Enter Your Username";
})
发布评论

评论列表(0)

  1. 暂无评论