Multiple form validation with same function - javascript

I am using form twice on same page.
HTML Code
<form action="post.php" method="POST" onsubmit="return checkwebform();">
<input id="codetext" maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
It's working fine with one form but when i add same form again then it stop working. The second form start showing error popup alert but even i enter text in form field.
JS Code
function checkwebform()
{
var codecheck = jQuery('#codetext').val();
if(codecheck.length != 5)
{
alert('Invalid Entry');
} else {
showhidediv('div-info');
}
return false;
}
How can i make it to validate other forms on page using same function?

As I commented, you can't have more than one element with the same id. It's against HTML specification and jQuery id selector only returns the first one (even if you have multiple).
As if you're using jQuery, I might suggest another approach to accomplish your goal.
First of all, get rid of the codetext id. Then, instead of using inline events (they are considered bad practice, as pointed in the MDN documentation), like you did, you can specify an event handler with jQuery using the .on() method.
Then, in the callback function, you can reference the form itself with $(this) and use the method find() to locate a child with the name codetext.
And, if you call e.preventDefault(), you cancel the form submission.
My suggestion:
HTML form (can repeat as long as you want):
<form action="post.php" method="POST">
<input maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
JS:
$(document).ready(function() {
//this way, you can create your forms dynamically (don't know if it's the case)
$(document).on("submit", "form", function(e) {
//find the input element of this form with name 'codetext'
var inputCodeText = $(this).find("input[name='codetext']");
if(inputCodeText.val().length != 5) {
alert('Invalid Entry');
e.preventDefault(); //cancel the default behavior (form submit)
return; //exit the function
}
//when reaches here, that's because all validation is fine
showhidediv('div-info');
//the form will be submited here, but if you don't want this never, just move e.preventDefault() from outside that condition to here; return false will do the trick, too
});
});
Working demo: https://jsfiddle.net/mrlew/8kb9rzvv/

Problem, that you will have multiple id codetext.
You need to change your code like that:
<form action="post.php" method="POST">
<input maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
<form action="post.php" method="POST">
<input maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
And your JS:
$(document).ready(function(){
$('form').submit(function(){
var codecheck = $(this).find('input[name=codetext]').val();
if(codecheck.length != 5)
{
alert('Invalid Entry');
} else {
showhidediv('div-info');
}
return false;
})
})

Related

How do i make a js code that redirects to a certain html page with a certain input?

let me explain this better, i would like to know how it's possible to create a js code that checks if an html input is correct and in case it is it redirects you to another page, here is what i tried based on what i managed to find out.
html part:
<form name="access" onsubmit="return validate()">
<input
type="text"
id="inputbox"
value="Password"
pattern="idkwhatishoouldwriteinhere"
/>
<input type="submit" value="Submit" />
</form>
js part:
function validate() {
if (document.access.Password.value != "idkwhatishoouldwriteinhere") {
alert("Wrong password");
document.access.Password.focus();
return false;
} else {
window.open("index.html");
}
}
in case you are wondering why i put the "answer" in the patter is because this is supposed to be a little easter egg and i feel like looking directly at the js is meaningless becuase it contains the link you should be redirected to.
enter code here
You need to give your input the name Password, otherwise document.access.Password is undefined.
function validate() {
if (document.access.Password.value != "idkwhatishoouldwriteinhere") {
alert("Wrong password");
document.access.Password.focus();
return false;
} else {
window.open("index.html")
}
}
<form name="access" onsubmit="return validate()">
<input type="text" id="inputbox" value="Password" name="Password" />
<input type="submit" value="Submit" />
</form>
<!-- password is "idkwhatishoouldwriteinhere" -->
You want this.
You had some issues with the id of the field and name etc
I also changed your inline code to eventListener which is the recommended method
Password is fred
window.addEventListener("load", function() {
document.getElementById("access").addEventListener("submit", function(e) {
const inputbox = document.getElementById("inputbox");
if (inputbox.value != "fred") {
alert("Wrong password");
inputbox.focus();
e.preventDefault(); // cancel submit
} else location.replace("index.html")
});
})
<form id="access">
<input type="password" id="inputbox" value="" placeholder="Password" />
<input type="submit" value="Submit" />
</form>
If you want to keep your code close to what you already have, I would adjust it like this. I would suggest storing your class names and ids as variables and then accessing them from the variable. Also there is no need to return false in your if. There are other good solutions on here but this one will keep your code pretty close. This will also ensure that you don't end up with a null value when accessing the value in your password field.
const passwordField = document.getElementById('inputbox');
function validate() {
if(passwordField.value != "idkwhatishoouldwriteinhere") {
alert( "Wrong password" );
passwordField.focus() ;
}
else {
window.open("index.html")
}
}
<form name="access" onsubmit="validate()" href="javascript:void(0)">
<input type="text" id="inputbox" value="Password" />
<input type="submit" value="Submit" />
</form>

Required Input Field + Onlick Button request

Currently I am trying to make my input field required.
<form name="myForm" method="post">
<input type="text" id="username" name="username" required>
<center><button id="process2" type="submit">Continue</button> </center>
</form>
When I have the above portion it works, however I need it to work whenever I have my button containing a onlick event. <button id="process2" type="submit" onclick="move()">Continue</button> how can I go about doing this?
The issue is currently - The onclick request will fire, and it'll prompt the required option, however the onclick request should not fire unless the required option is populated.
Instead of the onclick , you should listen for the form's submit, and call move() inside it
document.querySelector('form').addEventListener('submit', event => {
event.preventDefault();
console.log('submitted');
move();
});
function move() {
console.log('moving ..');
}
<form name="myForm" method="post">
<input type="text" id="username" name="username" required>
<button id="process2" type="submit">Continue</button>
</form>
Or you can just simply fire the move function but wrap your deserted effect inside if statement that will check if input is empty or not...
function move() {
element = document.getElementById("username").value;
if (element === "") {
console.log("input wasnt populated do something");
}
}
<form name="myForm" method="post">
<input type="text" id="username" name="username" required>
<center><button id="process2" type="submit" onclick="move()">Continue</button> </center>
</form>
Using jquery you can listen the submit event on form like then call move function to redirect to other page or whatever logic you want
$(document).on('submit','form',function(){
event.preventDefault();
// call move function here , move();
});

jQuery on click not returning any value

What I am trying to do is to get all inputs and data when someone click the submit button.
My code HTML is this:
<form id="form" action="index.php" method="POST" class="register" name="Register">
<label>Patient Name:</label>
<input id="pname" name="pname" placeholder="John Doe" type="text" data-role="justText" value=""><br><br>
<label>Phone Number:</label>
<input id="ptel" type="tel" name="ptel" value=""><br><br>
<label>Email:</label>
<input id="pemail" placeholder="example#gmail.com" type="email" value=""><br><br>
<button id="submit" class="submit" type="submit" name="register">Registrar</button>
</form>
Don't know if it's the best use the button or input tag for submit the form. And the jQuery to handle what I am trying to do is this:
jQuery.fn.extend({
hello: function () {
submitbutton = $(this).find('button').attr('id');
$inputs = $(this).find('input');
knowInputs = function() {
$inputs.each(function () {
console.log( $(this).attr('name') );
});
}
$('#'+submitbutton).on('click', function () {
knowInputs();
})
return this;
}
});
So, I put the form ID and init the function like this:
$(#form).hello();
P.D.: If I put the code knowInputs outside the on(click), it seems to work fine. My problem is when I am trying to gather all when clicking the submit button.
Any help shall be appreciated. Thanks in advance!
Forms have a native Javascript event, submit. jQuery also has a function, $.serialize which will turn a form into an encoded URL string, which is probably the most standard format you'd want it in. You can easily convert this into JSON or a JS Object.
$('#form').submit(function(e){
e.preventDefault();
return $(this).serialize();
});

Trigger html form submit as if you clicked on button (but without a button)?

If you have a <form> and a <button type='submit'> and you click on the submit button, it will do the default form validation, such as checking whether an <input> is required or not. It would normally say Please fill out this field.
However, if I programmatically submit the form through $("form").submit() for example, it would submit it without performing any checks.
Is there a simpler way to perform the default form validations using native JavaScript? There seems to be only checkValidity() on the form element which return true or false. And if I call the same native function on the input itself, it doesn't really do anything.
Here is a demo code of what I mean:
http://jsfiddle.net/totszwai/yb7arnda/
For those still struggling:
You can use the Constraint validation API - https://developer.mozilla.org/en-US/docs/Web/API/Constraint_validation
<div id="app">
<form>
<input type="text" required placeholder="name">
<input type="text" required placeholder="email">
</form>
<button id="save">Submit</button>
</div>
const form = document.querySelector("form");
document.getElementById("save").addEventListener("click", e => {
e.preventDefault();
if (form.checkValidity()) {
console.log("submit ...");
} else {
form.reportValidity();
}
});
Check out and play here: https://stackblitz.com/edit/js-t1vhdn?file=index.js
I hope it helps or gives you ideas. :)
I think this might be the answer you are looking for :
JavaScript :
document
.getElementById('button')
.addEventListener("click",function(e) {
document.getElementById('myForm').validate();
});
HTML :
<form id="myForm" >
First name: <input type="text" name="FirstName" required><br>
Last name: <input type="text" name="LastName" required><br>
<button id="button">Trigger Form Submit</button>
</form>
Demo : http://jsfiddle.net/2ahLcd4d/2/

When I press enter key, unable to login

I have been trying to log in to a offline HTML/CSS page using the enter key but unable to start with JavaScript which needs I'm sure.
But can log in using the mouse when I click the log in button which i have created ..
How do i use the enter key stroke to log in?
This is the javascript which I have hard coded for credential test which works using the mouse click.. I want it for the enter key.. Thank you.
<!DOCTYPE HTML>
<html>
<head>
<title>
Login page
</title>
</head>
<body>
<div align="center">
<div id="bor">
<h1>
Login Page
</h1>
<div>
<form name="login">
&nbsp<input type="text" placeholder="Enter the Username" name="user"/> <br />
<input type="password" placeholder="Enter the Password" name="pwd"/><br /><br />
<input type="checkbox" name="en" value="en" />Remember Me<br>
<input type="button" onclick="check(this.form)" value="Login"/>
<input type="reset" value="Cancel"/>
</form>
</div>
<script language="javascript">
function check(form)
{
if(form.user.value == "user" && form.pwd.value == "pwd")
{
window.open('inbox.html','_self')
}
else
{
alert("Error Password or Username")
}
}
</script>
Use the submit event handler. The click handler on an element will only fire if you click on it. What you are trying to do is submitting a form, but handling the form with javascript instead of on the server. I would recommend binding that dynamically, but as you have all javascript here inline, I'll give an example inline too.
You'll need to attach a submit event handler to the form element. If you do it inline, this will work with onsubmit="..." instead. The return is there to prevent/allow the form to be submitted to the server. If the function returns 'true', the form will be submitted to the server. If the function returns 'false', the form will not be submitted. You'll also need to change the type of your submit button to submit. This will tell the browser to submit the form if that button is clicked. Alternatively, if you press enter in an input field, the browser will see this as submitting the form too.
<form name="login" onsubmit="return check(this)">
&nbsp<input type="text" placeholder="Enter the Username" name="user"/> <br />
<input type="password" placeholder="Enter the Password" name="pwd"/><br/><br/>
<input type="checkbox" name="en" value="en" />Remember Me<br>
<input type="submit" value="Login"/>
<input type="reset" value="Cancel"/>
</form>
The javascript behind it will remain mostly the same. You'll notice that we passed this to the function. This will pass the element itself (in this case the form element) to the function. As said before, you'll need to return false. I've changed form to frm as form is a globally defined variable in some browsers.
function check(frm)
{
if(frm.user.value == "user" && frm.pwd.value == "pwd")
{
window.open('inbox.html','_self')
}
else
{
alert("Error Password or Username")
}
return false;
}
An example jsfiddle: http://jsfiddle.net/AS5t5/

Categories

Resources