Apologies if this question isn't layed out correctly (my first time using stack overflow).
I'm trying to validate if my inputs on a form are filled in when a user presses submit, it alerts the user when the inputs are empty but also when they are not, I'm not sure whats going wrong. Here is my Javascript:
<script>
function validation() {
var x = document.forms["bookingForm"]["id"].value;
if (x == "") {
alert("Ensure all fileds are filled");
return false;
} else {
sendSMS();
alert("Success");
return true;
}
}
</script>
Here is a link to an expanded part of the code for reference:https://pastebin.com/Dj5fA3gB
The general syntax for accessing a form element and element's value are:
document.forms[number].elements[number]
document.forms[number].elements[number].value
If you are using submitButton as in and you are calling validation on onSubmit of the form then you need to call event.preventDefault();
<!DOCTYPE html>
<html>
<body>
<form onsubmit="validation()" name="bookingForm">
First Name: <input type="text" name="id" value="Donald"><br>
Last Name: <input type="text" name="lname" value="Duck">
<input type="submit" value="Submit" />
</form>
<script>
function validation() {
event.preventDefault();
var x = document.forms["bookingForm"]["id"].value;
if (x == "") {
alert("Ensure all fileds are filled");
return false;
} else {
sendSMS();
alert("Success");
return true;
}
}
</script>
</body>
</html>
As suggested in my comment the most clean solution is to use the html attribute required by adding it to your inputs.
Looks something like this.
<form>
<input type="text" name="example" required>
<input type="submit" name="send">
</form>
The biggest advantage is that it works without any additional JS which is in my opinion always the prefered solution.
You didn't include return keyword in the form tag and adding unnecessary keyword "name" in the form tag.
<form onsubmit="return validation()" method="POST"
action="">
remove the "name" attribute from form tag and add action attribute.
Within the parenthesis in the action attribute, mention what happen if your validation success
Ex:(this code help you understand "action" attribute)
<form onsubmit="return productsvalidationform();" method="POST"
action="AddProductServlet">
when the form was successfully validated, I directed to AddProductServlet.(AddProductServlet is JSP servlet).
so that mention where do you need to redirect.
Related
I want to verify the inputs by javascrpit function perform() and move to a php page named i.php to save the datas in the databasse.
Here is the code:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="i.php" method="post">
<br>
Name <input type="text" name="name" id="name" >
<span id="err"></span>
</br>
<br>
Password <input type="Password" name="Password" id="password">
<span id="perr"></span>
</br>
<br>
Gender
<input type="radio" name="gender" id="gender" value="male">Male
<input type="radio" name="gender" id="gender" value="female">Female
</br>
<br>
Department <select name="department" id="department">
<option>------</option>
<option>ECE</option>
<option>BBA</option>
<option>ENG</option>
</select>
</br>
<br>
<button name="btn" type="button" id="btn" onclick="perform()" >Button</button>
<input type="submit" name="submit" value="Submit">
<input type="reset" name="reset" value="Clear">
</br>
</form>
<script type="text/javascript">
function perform()
{
var name = document.getElementById('name').value;
var pass = document.getElementById('password').value;
var dept = document.getElementById('department').value;
var gender = document.getElementsByName('gender');
var r =3;
if (name.length==0)
{
document.getElementById('err').innerHTML = "name not found";
r++;
}
if (pass.length<=6 || pass.length>=32 )
{
document.getElementById('perr').innerHTML = "password error";
r++;
}
if(r==3)
{
window.location= "i.php";
}
}
</script>
</body>
</html>*
In i.php page i used var_dump to see the datas whether it has been submitted or not. code of the i.php page:
<!Doctype html>
<html>
<head></head>
<body>
<?php
var_dump($_POST);
?>
</body>
</html>
But its showing arry(0) {}
looks like there nothing that has been submitted.
The issue is that you're redirecting with javascript, and losing the entire form and it's data by doing so.
When the form is valid, submit it rather than redirecting
function perform() {
var _name = document.getElementById('name').value;
var pass = document.getElementById('password').value;
var dept = document.getElementById('department').value;
var gender = document.getElementsByName('gender');
var valid = true;
if (_name.length === 0) {
document.getElementById('err').innerHTML = "name not found";
valid = false;
}
if (pass.length <= 6 || pass.length >= 32) {
document.getElementById('perr').innerHTML = "password error";
valid = false;
}
if (valid) {
document.querySelector('form').submit();
}
}
Note that name is not a good name for variables or form elements, as it already exists in window.name, and that a submit button can not be named submit as it overwrites the named form.submit() function
Another option would be to just remove all the javascript, and use HTML5 validation instead.
Use this code:
<form action="i.php" method="post" onsubmit="perform();">
And in javascript make these changes:
if(r!=3) {
alert('please complete the form';
return false;
}
Javascript doesn't send POST headers with window.location!
By using this code, you don't need to use a button, javascript perform() function runs when the submit button is clicked in the form.
If form values are entered truly, javascript perform() does not return and form submits; else, the function returns and prevents submitting the form.
The problem is you are not submitting the form you are just going to a different page with javascript without passing along any variables. so instead of doing
window.location= "i.php";
you should submit the form like so
document.getElementById("formId").submit();
so you should give the form the id formId
The problem is that you are merely redirecting to the i.php page without posting any data. Replace this line in your JS:
window.location = "i.php";
with this
document.getElementsByTagName('form')[0].submit();
This will find the form in your DOM and submit it along with the data that has been input, preserving the values for your action page.
You also need to rename your submit-button for this to work. Otherwise you will not be able to call the submit function on the form programmatically.
<input type="submit" name="submit-btn" value="Submit" />
should do the trick. However, I don't really see the point of the submit button in addition to your validation/submission button.
Full code sample of the solution here: https://jsfiddle.net/dwu96jqw/1/
by press btn you redirect only and your form dont submitted for transfer via _POST
you should change your code :
<form action="i.php" method="post" id ="form1">
and :
if(r==3)
{
form1.submit();
}
window.location will redirect you to the page, to preserve field values return it
if(r==3)
{
return true;
}
I have created a form in HTML and have use onblur event on each and every field and it is working very fine. The problem is when i click on submit button(which will send data to a servlet) the data is submitted even if it is invalid. Here is an example.
<html>
<head>
<script>
function check()
{
if(checkName()==true)
return true;
else{
alert('vhvh');
return false;
}
}
function checkName()
{
var uname=document.enq.Name.value;
var letters = /^[A-Za-z, ]+$/;
if(uname.match(letters))
{
document.getElementById('Name').style.borderColor = "black";
return true;
}
else
{
document.getElementById('Name').style.borderColor = "red";
//alert('Username must have alphabet characters only');
//uname.focus();
return false;
}
}
</script>
</head>
<body>
<form name="enq" method="post" action="Enquiry" onsubmit="check()">
<input class="textbox" id="Name"style="margin-top:10px;font-size:16px;" type="text" name="Name" placeholder="Full Name" onblur="checkName()" required /><br><br>
<input class="button" type="submit">
</form>
</body>
</html>
How can i resolve this issue?
use
<input class="button" type="button">
and put a onclick event like this:
<input class="button" type="button" onclick="this.submit()">
so you can manipulate data before you subimit it.
There is an "onsubmit" event that allows you to control form submission. Use it to call your validation functions, and only then decide if you want to allow the user to submit the form.
http://www.htmlcodetutorial.com/forms/_FORM_onSubmit.html
You have to use it in the following way if you want it to prevent the form submission:
<form onsubmit="return check()">
I have some javascipt code here that validates a user form. When the user inputs the correct answer it tells them and gives them the link to the next question. At least, that's what it is supposed to do. When i click the form it reloads the page but it should not because i added return false.
the div tra holds 35
and the div usermsg is the user inputted value.
<script>
$("#submit").click(function(){
var clientmsg6 = $("#usermsg").val();
var rightanswer = $("#tra").val();
if (clientmsg6<>rightanswer)
{
$("#confirm").html("<h2>Sorry, wrong answer.</h2>");
}
else
{
$("#confirm").html("<a href='#' onclick='play();' style='font-size:20px;' id='new1'>Click here for Question 2</a>");
}
return false;
});
</script>
Any ideas why this is not working?
It should be
if (clientmsg6 != rightanswer)
not
if (clientmsg6<>rightanswer)
To prevent a form submission, you need to return false on the form itself instead of on the submit button. Your code should become:
HTML
<form action="page.php" method="post">
<input id="usermsg" type="text" name="answer" />
<input id="submit" type="submit" value="Submit" />
</form>
JS (please note the line where you have clientmsg6, you have a syntax error)
$("#myform").on('submit', function(){
var clientmsg6 = $("#usermsg").val();
var rightanswer = $("#tra").val();
if (clientmsg6 != rightanswer) { //This line was also wrong, should be != instead of <>
$("#confirm").html("<h2>Sorry, wrong answer.</h2>");
}
else {
$("#confirm").html("<a href='#' onclick='play();' style='font-size:20px;' id='new1'>Click here for Question 2</a>");
}
return false;
});
Alternatively, you can keep your existing code by changing your submit button to be just a plain old button, but you will lose the extra functionality of the user being able to hit the enter key and performing the same action.
<form action="page.php" method="post">
<input id="usermsg" type="text" name="answer" />
<input id="submit" type="button" value="Submit" />
</form>
Instead of using .html(), try using .text()
if #submit is a link tag otherwise use the form ID and the submit event
$("#submit").click(function(e){
e.preventDefault()
...
...
...
});
You need to attach handlers once the document has finished loading.
Wrap your script in the following
<script>
$(function() {
// script
});
</script>
That is the thing.
My head:
<script language="JavaScript">
function checkIt(){
var pass = document.form1.value;
if (pass == "1234")
{
alert("Please input a Value");
return false;
}
else
{
alert('Code has accepted : you can try another');
return true;
}
}
window.onload = checkIt();
</script>
My body:
<form action="#" method="post" id="form1" onsubmit="checkIt();">
<input type="password" id="sn" name="sn" placeholder="Enter Your Password">
<img src="ok.gif" onclick="submit();" style="cursor: pointer;">
</form>
Can anybody tell me what I am doing wrong? It is not working. I need it to be able to compare entered value named sn, with var pass.
I am noob and not a native speaker, so stay calm, please:)
Fix your script
// to get the input value
var pass = document.getElementById("sn").value;
And on your form you have to return the result of the function
onsubmit="return checkIt();"
Also remove window.onload = checkIt(); that will validate the form before you enter any value
try the following:
Javascript
<script language="JavaScript">
function checkIt(){
var pass = document.getElementById("sn").value;
if (pass == "1234")
{
alert("Please input a Value");
return false;
}
else
{
alert('Code has accepted : you can try another');
return true;
}
}
</script>
HTML
<form action="#" method="post" id="form1" onsubmit="return checkIt();">
<input type="password" id="sn" name="sn" placeholder="Enter Your Password">
<img src="ok.gif" onclick="document.getElementById("form1").submit();" style="cursor: pointer;">
</form>
Try var pass = document.getElementById('sn').value;
onclick="form1.submit()" and onsubmit="return checkIt()"
You are calling the function, not assigning it
window.onload = checkIt();
Needs to be
window.onload = checkIt;
But do you really want to run the validation when the page loads? You probably do not need this line at all. Delete it!
You are not cancelling the submit event. Your function returns true or false, but you are not handling it.
<form action="#" method="post" id="form1" onsubmit="checkIt();">
Your form tag needs to be
<form action="#" method="post" id="form1" onsubmit="return checkIt();">
notice the return statement. That will cancel the submission.
What is submit()? The page is probably throwing an error which you would be able to see in the console. You need to tell it what to submit. That means referencing a form.
<img src="ok.gif" onclick="submit();" style="cursor: pointer;">
There is no method called submit() in your code. Maybe you want to call the form submission.
<img src="ok.gif" onclick="doucment.form1.submit();" style="cursor: pointer;">
You would probably be better off using input with type="image" to submit the form.
<input type="image" src="ok.gif" />
Using the input means no JavaScript is needed to submit the form. So remove the image tag and add the input element!
And finally you are reading the value of the form, not the input
var pass = document.form1.value;
You want the input!
var pass = document.form1.sn.value;
And it makes no sense why 1234 would fail, but all other things pass. Don't you have the logic wrong?
You need to learn how to debug, use the browser's console and learn to use console.log() to see the data. Set break points and walk through the code so you can inspect what is going on. JavaScript 101.
I am implementing search and when i put nothing in search box this must be remain on same page what will be java script coding for that.
i just create function in java script and return false if string is null on button click it is not working.
As your text makes no sense I must guess what you want to say.
You want your search form to not submit if field is empty and user clicks on search
on form attributes you use onsubmit
<form action="/" method="post" onsubmit="return checkForm(this)">
<input type="text" name="searchText" id="searchText" />
<input type="submit" value="search" />
</form>
now you check if searchText has any text and return true or false
<script type="text/javascript">
function checkForm(form){
if(form.searchText.value == ''){
return false;
}
return true;
}
</script>
I recommand to use JQuery for this kind of functionality, eg:
for the following form
<form action="/myaction" method="post" id="myForm">
<input type="text" value="" name="something1" />
<input type="text" value="" name="something2" />
<input type="submit" />
</form>
and in the same HTML file or in a separate JS file included via html HEADERS :
$(function () {
$("#myForm").submit(function() {
return ($(this).children("input").val()=='') ? false : true;
});
});
or if you don't like ternary expression:
$(function () {
$("#myForm").submit(function() {
doSubmit = true;
if ($(this).children("input").val()=='') {
doSubmit = false;
}
return doSubmit;
});
});
Using it this way, the function assume that all the fields of the form are not empty before posting data.
One other advantage of this method is that it doesn't alter the view code (this is some no intrusive javascript fashion) and can be much more easy to work with.
Hope it help.