简体   繁体   中英

Using JavaScript to check for user-input

I'm submitting a form with input text to my server through my web client. What I'm trying to do is to check whether the user has passed in text into the input field before sending the form by hitting the submit button.

What I have tried so far:

 var form = document.getElementById("id"); document.getElementById("id").addEventListener("click", function() { var input = document.getElementById("content").value; if (input == "") { alert("write something in the textfield"); } else { form.submit(); } });
 <form action="" method="post" id="id"> <input type="text" name="name" id="content"> <button type="submit" id="submit-id">submit text</button> </form>

Any good tips on how to do this?

You want preventDefault on the submit event

 document.getElementById("id").addEventListener("submit", function(e) { const input = document.getElementById("content").value; if (input.trim() === "") { alert("write something in the textfield"); e.preventDefault() } });
 <form action="" method="post" id="id"> <input type="text" name="name" id="content"> <button type="submit" id="submit-id">submit text</button> </form>

Alternatively just add required attribute - no need for script:

 <form action="" method="post" id="id"> <input type="text" name="name" id="content" required> <button type="submit" id="submit-id">submit text</button> </form>

I'm submitting a form with input text to my server through my web client. What I'm trying to do is to check whether the user has passed in text into the input field before sending the form by hitting the submit button.

What I have tried so far:

 var form = document.getElementById("id"); document.getElementById("id").addEventListener("click", function() { var input = document.getElementById("content").value; if (input == "") { alert("write something in the textfield"); } else { form.submit(); } });
 <form action="" method="post" id="id"> <input type="text" name="name" id="content"> <button type="submit" id="submit-id">submit text</button> </form>

Any good tips on how to do this?

you can use the simple code snippet instead :

 <form action="" method="post" id="id"> <input type="text" name="name" id="content" required> <button type="submit" id="submit-id">submit text</button> </form>

 function submitIt(e) { var formData = new FormData(e); var object = {}; formData.forEach(function(value, key) { object[key] = value; }); if (object.name == "") { alert("null"); } else { alert("ok"); return true; } return false; }
 <form onsubmit="return submitIt(this)"> <input type="text" name="name"> <button>submit text</button> </form>

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