JavaScript Form Validation - What is wrong with this code? [duplicate] - javascript

This question already exists:
Javascript Form Validation - What is wrong with my code?
Closed 8 years ago.
I am simply adding text into the input field for practice. It seems that when I press submit, the text appears in the input field for a short second then disappears. Could someone please tell me why this is happening? How can I get the messages to stay?
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<script src="EventUtil.js"></script>
</head>
<body>
<form>
<input type="text" name="poop1"> <br>
<input type="text" name="poop1"> <br>
<input type="text" name="poop1"> <br>
<input type="text" name="poop1"> <br>
<input type="submit" value="submit" id="btn">
</form>
<script type="text/javascript">
EventUtil.addHandler(window,"load", function() {
var btn = document.getElementById("btn");
EventUtil.addHandler(btn,"click",function(){
var i;
for (i=0; i<document.forms[0].elements.length-1; i++){
if (document.forms[0].elements[i].value == ""){
document.forms[0].elements[i].value = "fill this poop in";
}
}
})
})
</script>
</body>
</html>

The issue is that you're submitting the form, which reloads the current page. That's why you see the values for only a moment.
To fix it, use a <button type="button"> instead of an <input type="submit">.

You should put the listener on the form's submit handler, not the submit button, as the form can be submitted without clicking the button. Either add an ID to the form, or use the document's forms collection:
var form = document.forms[0];
or
var form = document.getElementById('formID');
As noted in other answers, the form is submitting so the page refreshes. To cancel submit, return false from the listener.
Within the listener, this should reference the form:
EventUtil.addHandler(form, 'submit', function(){
var control, controls = this.elements;
for (var i=0, iLen=controls.length; i<iLen; i++) {
control = controls[i];
if (control.type == 'input' && control.type == 'text' && control.value == '') {
control.value = 'fill this shit in';
return false;
}
}
});

Why don't you just use the required attribute on the form elements

Related

What is the difference between using onsubmit directly in DOM vs accessing it from JavaScript? [duplicate]

This question already has answers here:
onclick="" vs event handler
(9 answers)
Closed 1 year ago.
I'm relatively new to JS and my goal is to put focus on the input field if there is an error (after validation) and I realise that if I write onsubmit=validateFunction() directly in the HTML tag for form, (I assume) it refreshes the page and doesn't put the focus on the input field like how I wanted. Comparing this with calling it in JS, for eg, document.getElementById("myForm").onsubmit = validateFunction; I will be able to get it to work like how I wanted it to. I don't understand the difference between the two, why does one (onSubmit in form tag) refreshes the page (or simply does not put focus on the input field) and the other (calling from JS) works like how I wanted it to?
Here is an example for more clarification on the question:-
function validateFunction() {
const name = document.getElementById("name");
if (name.length < 5) {
alert("Not valid!");
name.focus();
name.select();
return false;
} else {
return true;
}
}
<form id="myForm" action="" onsubmit="validateFunction();">
<label>Name: <input type="text" id="name"></label>
<button type="submit">Submit</button>
</form>
compared to (works):
<form id="myForm" action="">
<label>Name: <input type="text" id="name"></label>
<button type="submit">Submit</button>
</form>
<script type = "text/javascript" >
document.getElementById("myForm").onsubmit = validateFunction;
</script>
If you are using the onsubmit attribute, you have to return the returned value of the function.
You also should be checking the length of the input's value property, not the input element itself.
function validateFunction() {
const name = document.getElementById("name");
if (name.value.length < 5) {
alert("Not valid!");
name.focus();
name.select();
return false;
} else {
return true;
}
}
<form id="myForm" action="" onsubmit="return validateFunction()">
<label>Name: <input type="text" id="name"></label>
<button type="submit">Submit</button>
</form>

Using ENTER key to replace button click?

<body>
<form>
<label>enter number here: </label>
<input type="number" id="text"/>
<button type="button" id="btn" onclick="calc()">read</button>
</form>
<script>
document.getElementById("text").addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("btn").click();
}
});
</script>
<br>
<label id = "calculated"></label>
<script>
function calc() {
let inputValue = document.getElementById("text").value;
document.getElementById('calculated').innerHTML = 'your number: ' + inputValue;
}
</script>
</body>
I have a very simple HTML file with minimal javascript included. When I click the button, it works perfectly. But when I hit the ENTER on the keyboard to simulate the button click, it will also run through the code, but then an error happens at the end.
On Firefox and Chrome, it'll return an error "Not Found". On w3schools, it'll return "The file you asked for does not exist". And on stackoverflow, it'll just disappear.
What am I missing? Where is the error? What's the trick to making the ENTER key act just like the mouse click?
HTML form has onsubmit attribute on them. onsubmit handles the enter functionality. You have to set the type="submit" on the button, also you need to set the onsubmit on form passing the event to your function so that you can prevent the default action of the form ( that is to send the request to backend ) by doing e.preventDefault.
<body>
<form onsubmit="calc(event)">
<label>enter number here: </label>
<input type="number" id="text"/>
<button type="submit">read</button>
</form>
<br>
<label id = "calculated"></label>
<script>
function calc(e) {
// Will stop the form from sending the request to backend
e.preventDefault()
let inputValue = document.getElementById("text").value;
document.getElementById('calculated').innerHTML = 'your number: ' + inputValue;
}
</script>
</body>
If you want to just prevent ENTER from doing anything including running the code....
The following code (yours with a couple more lines... will prevent Enter from doing anything:
<body>
<form onsubmit="return mySubmitFunction(event)">
<label>enter number here: </label>
<input type="number" id="text"/>
<button type="button" id="btn" onclick="calc()">read</button>
</form>
<script>
document.getElementById("text").addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
return false;
//document.getElementById("btn").click();
}
});
</script>
<br>
<label id = "calculated"></label>
<script>
function mySubmitFunction(e) {
e.preventDefault();
return false;
}
function calc() {
let inputValue = document.getElementById("text").value;
document.getElementById('calculated').innerHTML = 'your number: ' + inputValue;
}
</script>
Why was this happening? since the form element itself has a submit and the enter key is a key pressed which also does a form submit.... so you need to prevent the form from submitting... mySubmitFunction() <- this prevents the form from submitting ... and a change to your keyup event listener - if you do not want enter to even create the click you change this:
event.preventDefault();
document.getElementById("btn").click();
to this :
event.preventDefault();
return false;
//document.getElementById("btn").click();
As I have already did in the code example. or leave it like you had(the event listener keyup) and the Enter key will only act as a click.

How to dynamically keep track of user inputs in JavaScript?

Does anyone have any idea to dynamically keep track of user inputs in a form? I learned how to disable a button and if users want to enable it, they would just have to fill in the input fields. While this works, if a user decides to backspace and go back to a clear field, the button is still enabled. I wanted to get some insight or ideas to keep track of user inputs dynamically.
I'm a bit new to JS so I just wanted some ideas. Is it possible to use for loops/forEach methods to iterate through the input fields? Or what approach do you recommend on taking?
HTML:
<form class="container">
<input type="text" class="input" />
<input type="email" class="input" id="input" />
<button type="submit" id="submitButton" href="index.html" disabled>
Submit
</button>
</form>
JavaScript:
document.getElementById("input").addEventListener("keyup", function() {
var inputs = document.querySelectorAll("input");
if (inputs != "") {
document.getElementById("submitButton").removeAttribute("disabled");
} else if ((inputs = "")) {
document.getElementById("submitButton").setAttribute("disabled", null);
}
});
Here is the solution of your problem.
document.addEventListener("keyup", function() {
var inputs = document.querySelectorAll("input");
var emptyFillExists = false;
for (let index = 0; index < inputs.length; index++) {
if (inputs[index].value.length === 0) {
emptyFillExists = true;
break;
}
}
if (!emptyFillExists) {
document.getElementById("submitButton").removeAttribute("disabled");
} else {
document.getElementById("submitButton").setAttribute("disabled", null);
}
});
<form class="container">
<input type="text" class="input" />
<input type="email" class="input" />
<button type="submit" id="submitButton" href="index.html" disabled>
Submit
</button>
</form>
There are a few things wrong with your codes:
You assume inputs as strings. It isn't. It's an array.
You track keyup event for only 1 input. You should track keyup event for all inputs instead.
Here's what I'd suggest you do:
Add event listener keyup for the form.
Interate through each input and check.
function areInputsValid() {
// Iterate through every input and check its value
var inputs = document.querySelectorAll('input');
for (var i = 0; i < inputs.length; i++)
if (inputs[i].value == '')
return false;
return true;
}
// Get the form element
var form = document.getElementsByTagName('form')[0];
// Add event listener
form.addEventListener('keyup', function() {
// Are the inputs valid?
if (areInputsValid())
document.getElementById("submitButton").removeAttribute("disabled");
else
document.getElementById("submitButton").setAttribute("disabled", null);
})
EDIT: as charlietfl pointed out, there are bugs in my previous answer.

Onclick event; If and Else

All right so I am doing a javascript code for a login type form and it will lead you to a new page. Here it is:
function submit1()
{
var x=document.getElementById("username");
var y=document.getElementById("password");
if (x.value=="username" && y.value=="password")
{
window.location="Example.php";
}
else
{
window.alert=("The information you have submitted is incorrect and needs to be submitted again!");
}
}
When ever I am hitting the submit button it takes me straight to the page instead of checking to see if it right. Please help!
Thank you in advanced! To let you know this is not a permanet login page!
The easy way to do this would be to use a button input:
<input type="button" value="Check" onclick = "submit1();" />
The alternative is to prevent this default behavior of a submit type input, by making the handler return false. Your HTML would look like this:
<input type="submit" value="Check" onclick = "return submit1();" />
Your function would need to be changed a well (considering the fact that you want it to not redirect). I am assuming you want to preserve data entered, so I am not going to use window.location to redirect. Instead, I am going to allow the form to be submitted:
function submit1()
{
var x=document.getElementById("username");
var y=document.getElementById("password");
if (x.value == "username" && y.value == "password") {
window.alert=("The information you have submitted is incorrect and needs to be submitted again!");
return false;
}
}
<html>
<head>
<title>
Login page
</title>
</head>
<body>
<h1 style="font-family:Comic Sans Ms;text-align="center";font-size:20pt;
color:#00FF00;>
Simple Login Page
</h1>
<form name="login">
Username<input type="text" name="userid"/>
Password<input type="password" name="pswrd"/>
<input type="button" onclick="check(this.form)" value="Login"/>
<input type="reset" value="Cancel"/>
</form>
<script language="javascript">
function check(form)/*function to check userid & password*/
{
/*the following code checkes whether the entered userid and password are matching*/
if(form.userid.value == "myuserid" && form.pswrd.value == "mypswrd")
{
window.location="Example.php"; /*opens the target page while Id & password matches*/
}
else
{
alert("Error Password or Username")/*displays error message*/
}
}
</script>
</body>
</html>
The event needs to cancel the default event and return false. This will prevent the form from submitting.
HOWEVER, it should be a non-issue if the form submits anyway, because JavaScript CANNOT be trusted and therefore you MUST validate all input server-side.
<form method="post" action="." id="myform">
<!-- form contents --->
</form>
<script type="text/javascript">
(function () {
var f = document.getElementById('myform'), // get your form element
x = document.getElementById('username'),
y = document.getElementById('password'),
handler;
handler = function (e) {
e.preventDefault(); // stop submit
if (x.value=='username' && y.value=='password') {
window.location = 'Example.php';
} else {
window.alert('The information...');
}
};
// listen to submit event
if ('addEventListener' in f) {
f.addEventListener('submit', handler, false);
} else { // handle also IE...
f.attachEvent('submit', function () {
handler(window.event);
});
}
}());
</script>
anyway it looks like you're trying to check login/password from JS what is not greatest idea (anyone can just look into source and read it)

Javascript disabling input fields

I am looking for a javascript function. which will disable the entered (filled) text field on submit. So when the user logs in back the filled text box has to remain disabled. I have tried a code, but here what happens is on clicking the sumbit the contents in the text field gets deleted.
<html>
<head>
<script>
function enableDisable(){
var disable = true;
var arglen = arguments.length;
var startIndex = 0;
var frm = document.example1;//change appropriate form name
if (arglen>0){
if (typeof arguments[0]=="boolean") {
disable=arguments[0];
if (arglen>1) startIndex=1;
}
for (var i=startIndex;i<arglen;i++){
obj = eval("frm."+arguments[i]);
if (typeof obj=="object"){
if (document.layers) {
if (disable){
obj.onfocus=new Function("this.blur()");
if (obj.type=="text") obj.onchange=new Function("this.value=this.defaultValue");
}
else {
obj.onfocus=new Function("return");
if (obj.type=="text") obj.onchange=new Function("return");
}
}
else obj.disabled=disable;
}
}
}
}
</script>
</head>
<body>
<form name="example1">
Text Field: <input type="text" name="text1">
<br>
<input type="submit" name="control1" onclick="enableDisable(this.submit,'text1','submit','select1')">
</form>
</body>
</html>
please do guide.
Make sure your submit function returns false if you don't want the page to refresh. The code you're looking for is document.getElementById('insertIdOfTextFieldHere').style.readonly = "readonly";

Categories

Resources