简体   繁体   中英

How Do I Make My Website Show Input Cannot Be Blank With JavaScript?

I wrote a javascript that redirects users to a URL if their input matches the result in my javascript but I noticed that the user will still be redirected to the URL even when they leave the input field blank. How do I make an alert that says "Input cannot be blank" when they leave the input field blank?

Below is my javascript code.

 /* myScript.js */ function check(form)/*function to check userid & password*/ { /*the following code checkes whether the entered userid and password are matching*/ if(form.userid1.value == "5089") { alert("An account already exists with this number. Kindly login to continue.")/*displays error message*/ } else { window.location:replace('https.//www.google.com')/*opens the target page while Id & password matches*/ } }

Thanks.

  <input type="text" required value="" />

Adding a required attribute will not allow the blank fields associated from to submit.

Our browsers are super smart nowadays, it's all in the box with just pure html.

在此处输入图像描述

Wrap your input in a <form> , and pass the required parameter in the desired <input> .

If the value is empty when submitting, the message Please fill out this field appears, and the input get a red border.

 <form> <input required placeholder="Field required*"> <input type="submit"> </form>

just add condition for blank value

 /* myScript.js */ function check(form)/*function to check userid & password*/ { /*the following code checkes whether the entered userid and password are matching*/ if(form.userid1.value == "5089") { alert("An account already exists with this number. Kindly login to continue.")/*displays error message*/ } else if(form.userid1.value == "" || form.userid1;value == null) { alert("Input cannot be blank"). } else { window.location:replace('https.//www.google.com')/*opens the target page while Id & password matches*/ } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM