I'm having a problem with a simple html login page I made, where when I submit the login form with invalid credentials the form still submits, even though my validation method is executing the "return false" command. I know that this question has been asked a multitude of times here, but none of the answers to those questions have helped me.
My html form is as follows:
<form onSubmit="return validateForm();" method="get" action="TestPage.html">
<div id="centralPoint" class="frame">
<select id="centralPointSelect" data-inline="true" data-mini="true" data-native-menu="false" name="centralPoint"></select>
</div>
<div id="credentialsFrame" class="frame">
<input id="userField" type="text" name="Username" />
<input id="passField" type="password" name="Password" />
</div>
<div id="errorMsg"></div>
<input id="loginBtn" type="submit" value="Login" />
<div id="rememberMe" class="frame">
<input type="checkbox" id="checkbox-1" class="custom" data-mini="true" name="rememberMe" />
<label for="checkbox-1">Keep me signed in</label>
</div>
<div id="forgotPassFrame">
<input id="forgotPass" type="button" data-mini="true" value="Forgot password?" />
</div>
</form>
And here is my javascript method. Note that even if the only line of code in here is "return false;" the form still submits. I've also checked in firebug to make sure that the method is actually being called and that it is indeed returning false, and it all checks out.
function validateForm()
{
var usernameTxt = $("#userField").attr("value");
var passwordTxt = $("#passField").attr("value");
if (usernameTxt == "" || passwordTxt == "" || (usernameTxt == userLbl && passwordTxt == passLbl))
{
$("#errorMsg").html("Please enter a username and password.");
return false;
}
}
Is there something really obvious that I'm missing? I'm not binding the onsubmit event in any way other than what you can see in the html form tag, nor am I assigning any click handler to the submit button.
It might be relevant that I'm using JQuery mobile, is it possible that this is doing something with my form?
If you want to handle form submission on your own, you will need to add the data-ajax="false" attribute to the <form> tag so jQuery Mobile leaves it alone.
To prevent form submissions from being automatically handled with
Ajax, add the data-ajax="false" attribute to the form element. You can
also turn off Ajax form handling completely via the ajaxEnabled global
config option.
Source: http://jquerymobile.com/demos/1.1.0/docs/forms/forms-sample.html
Here is a demo of your form but with the above attribute added: http://jsfiddle.net/XtMw9/
Doing this means that you will have to manually submit your form:
function validateForm()
{
var usernameTxt = $("#userField").val();
var passwordTxt = $("#passField").val();//notice the use of .val() instead of .attr()
if (usernameTxt == "" || passwordTxt == "" || (usernameTxt == userLbl && passwordTxt == passLbl))
{
$("#errorMsg").html("Please enter a username and password.");
return false;
}
var $form = $('form');
$.ajax({
url : $form.attr('action'),
type : $form.attr('method'),
data : $form.serialize(),
success : function (response) { ... },
error : function (a, b, c) { console.log(b); }
});
}
Explanation
This works because by default jQuery Mobile will attempt to submit any form via AJAX. Using the data-ajax="false" attribute we can tell jQuery Mobile to leave a specific form alone so we can submit it on our own.
In validateForm() function, you've used two undefined variables(userLbl and passLbl).
Define value for the variables and check.
Related
I would like to 'post' a form with vanilla JS. There are other questions similar, but I cannot get mine to work. The data is simply not passing to the controller.
I have several options for user on page, displayed as buttons. When the user clicks one button, a hidden form gets filled, and then the JS will submit the form to the controller.
the hidden form below:
[for testing, I have not 'hidden' the form fields yet, so I can monitor the correct information is getting to the form]
<form action="RetailTimePriceDisplayOne" method="post" id="postForm" name="postForm">
<input type="text" id="fmZero" value="#ViewBag.zero" />
<input type="text" id="fmVehicle" />
<input type="text" id="fmTeam" />
<input type="text" id="fmTLabor" />
<input type="text" id="fmRouteCost" />
<input type="text" id="fmRouteD" value="#ViewBag.vehicleMile"/>
<input type="text" id="fmRouteT" value="#ViewBag.vehicleTime"/>
</form>
My JS:
<script>
function fillForm(vehicleType, teamCount, travelLabor, routeCost) {
document.getElementById("fmVehicle").value = vehicleType;
document.getElementById("fmTeam").value = teamCount;
var x = #ViewBag.rateTravelDrvr;
if (teamCount > 1) {
x = #ViewBag.rateTravelDrvr + (#ViewBag.rateTravelCrew * (teamCount - 1));
}
document.getElementById("fmTLabor").value = x;
var y;
if (vehicleType == "V") {
y = #ViewBag.vVPrice;
}
if (vehicleType == "H") {
y = #ViewBag.vHPrice;
}
if (vehicleType == "T") {
y = #ViewBag.vTPrice;
}
document.getElementById("fmRouteCost").value = y;
SubmitForm();
}
function SubmitForm() {
var myForm = document.getElementById('postForm');
//document.forms["postForm"].submit();
myForm.method = 'post';
myForm.submit();
}
</script>
The form gets filled correctly, but no data is submitted to the controller. You can see that I played around with it a bit. One thought I had was that the method was changing to 'get' and that by explicitly specifying the method, I might solve the issue. But no such luck. Thanks!
EDIT:
As requested, one of the 6 buttons on the page that fire the JS function.
<button class="btn btn-secondary btn-lg" style="width:100%; height:100%;" onclick="fillForm('T',3)">
<strong>#ViewBag.TrkThr</strong>
<p>with 3 persons</p>
<p>+ #ViewBag.TrkMinute per labor minute*</p>
</button>
Usually when I want to submit the form, I am using button, then do onClick event
The "name" of the inputs wasn't defined, and hence data wasn't getting posted.
I have this form in html and I want to validate this form when the user press #btnPopup, this button is not a submit one. How can I do this without using jQuery validation plugin, on a click button?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="frmUsers" data-userid="">
<img id="btnClose" src="resources/img/close_window.png">
<h2 id="popupTitle"></h2>
<ul>
<li>
<label for="username">Username:</label>
<input type="text" id="username" name="txtUsername" placeholder="Please select username" required/>
</li>
<li>
<label for="level">Level:</label>
<input type="number" id="level" name="txtLevel" placeholder="Please select level" required/>
</li>
<li>
<label for="registrationStatus">RegistrationStatus:</label>
<select name="txtRegistrationStatus" id="registrationStatus" placeholder="Please select registration status" class="required">
<option value="Registered">Registered</option>
<option value="Unregistered">Unregistered</option>
</select>
</li>
<li>
<label for="registrationDate">RegistrationDate:</label>
<input type="text" id="registrationDate" name="txtRegistrationDate" placeholder="Please select date" required/>
</li>
<div class="btnZone">
<input class="btnDown" type="button" value=" " id="btnPopup" />
<input class="btnDown" type="button" value="Cancel" id="btnCancel">
</div>
</ul>
</form>
You can use ajax by sending your form input in parameters to achieve what your want and attach an event to your button.
$('#btnPopup').on('click', function(){
// Fields validation
if( validation ){
$.ajax({
method: "POST",
url: "your_url",
dataType: 'json',
data: {
'username' : $('#username').val(),
'level' : $('#level').val()
...
}
})
.done(function( result ) {
// Do something
})
.fail(function(result, textStatus) {
// Do something when error happened
});
}else{
// Do something when your validations are bad.
}
});
Don't forget to validate your parameter server side. Validation client side can be by passed easily. After that you can get the server response inside the ajax success callback
You can submit your Form by attaching a "Click" listener on your "#btnPopup" and adding a simple submit inside it:
var myButton = document.getElementById("btnPopup");
myButton.addEventListener("click" , function(){
/*
--Your Validation logic goes here--
*/
// You submit the Form when the Validation is over.
document.getElementById("frmUsers").submit();
});
Now you can write your own Validation functions depending on what you want to validate your form against. A really simple and very basic validation would be to create a general function and validate each field on by one like the following :
function validate(inputField){
var myInputField = document.forms["frmUsers"][inputField].value;
// Add some simple Validation Rules
if(myInputField == null || myInputField == ""){
// Do Something if validation fails [Eg: alert('error!!!');]
return false;
}
}
You can use the above function like :
validate("txtUsername");
You can apparently make a loop and pass through each field in your Form and validate it. Generally there are a lot of ways to validate a Form , the above example will get you in the right track though.
Important: This is a Client-Side validation though. Keep in mind that in 99 cases out of 100 you really need to have a Server-Side validation configured too. Client-Side validation is not 100% secure.
Yes, you can do it. below is sample code which you can tweek and use
function validateForm() {
var x = document.forms["frmUsers"]["registrationDate"].value;
if (x == null || x == "") {
alert("Registration date must be filled out");
return false;
}
}
<input class="btnDown" type="button" value=" " id="btnPopup" onclick="return validateForm();/>
I'm creating a simple website and a html page on it which contains a table that shows products. I load this table using AJAX and it work properly. Here is a screenshot:
Under the table I have buttons which perform CRUD operations using AJAX.
They communicate to a php script on a server outside of my domain using GET method.
When I click on Add product it opens a form with a button that whose onclick event calls a function which adds a product using AJAX. But, when I click, the whole page reloads and the product is not added. If I put the value that says wheter the call is async to false, it works as intended and the product is added to the table, however that is not the point of AJAX.
This is my code for adding a product(delete and update are almost the same).
<div id="addProductPopup">
<div id="popupContact">
<form id="form" method="post" name="form">
<img id="close" src="/servis/Resursi/Slike/close.png" onclick ="hide('addProductPopup');">
<h2>Dodavanje proizvoda</h2>
<hr>
<input id="name" name="naziv" placeholder="Naziv proizvoda" type="text" required>
<input id="kolicina" name="kolicina" placeholder="Količina proizvoda" type="text" required>
<input id="url" name="url" placeholder="URL slike" type="text" required>
<input type="submit" value="Pošalji" class="popupButtons" onclick="addProduct()">
</form>
</div>
When I click on submit this function is called:
function addProduct(){
var isValid = true;
var url = "http://zamger.etf.unsa.ba/wt/proizvodi.php?brindexa=16390";
var amount = document.form.kolicina.value;
var naziv = document.form.naziv.value;
var slikaurl = document.form.url.value;
var validity = validateFields(naziv, slikaurl, amount);
if(!validity) return false;
var product = {
naziv: naziv,
kolicina: amount,
slika: slikaurl
};
var requestObject = new XMLHttpRequest();
requestObject.onreadystatechange = function(event) {
if (requestObject.readyState == 4 && requestObject.status == 200)
{
loadProducts();
event.preventDefault();
}
}
requestObject.open("POST", url, true);
requestObject.setRequestHeader("Content-type","application/x-www-form-urlencoded");
requestObject.send("akcija=dodavanje" + "&brindexa=16390&proizvod=" + JSON.stringify(product));
}
It is because you are not preventing the default action of the submit button click.
You can return false from an event handler to prevent the default action of an event so
<input type="submit" value="Pošalji" class="popupButtons" onclick="addProduct(); return false;">
But since you have a form with a submit button, I think it will be better to use the submit event handler like
<form id="form" method="post" name="form" onsubmit="addProduct(); return false;">
....
<input type="submit" value="Pošalji" class="popupButtons">
Your problem is that your submit button still executes a real submit. You could change your addProducts method. The method have to return false to prevent the real submit.
Submit button performs default Submit action for HTML code.
Try to change Submit tag into Button tag. Or after AddProduct() in OnClick JS Action put
return false;
Simple Change put input type="button" instead of tpye="submit"
<input type="button" value="Pošalji" class="popupButtons" onclick="addProduct()">
I searched on stackoverflow and find some answers, but I tried everything.
Maybe it is just a small, or a few small mistakes, but I can't find them.
I also tried on jsFiddle!
<form class="search" onsubmit="return false;" method="get" action="index.html">
<input class="text" type="text" onblur="if(this.value == ''){this.value = this.defaultValue;}" onfocus="if(this.value == this.defaultValue){this.value = '';}" onkeydown="if (event.keyCode == 13) { this.form.submit(); return false; }" value="Nachname" name="inputNachname" />
<input class="text" type="text" onblur="if(this.value == ''){this.value = this.defaultValue;}" onfocus="if(this.value == this.defaultValue){this.value = '';}" onkeydown="if (event.keyCode == 13) { this.form.submit(); return false; }" value="Vorname" name="inputVorname" />
<input type="hidden" value="search" name="query" />
<button id="searchButton2" onmouseover="this.style.cursor = 'pointer';" onclick="form.submit();" value="Go" type="button">SUCHE</button>
</form>
I want to have a function, which returns false:
<form class="search" onsubmit="return go_search();" method="get" action="index.html">
and this is the function:
function go_search(){
alert('abort');
return false;
}
jsFiddle
Maybe anyone can find some mistakes or find a better way to do this?
There are two problems with your fiddle.
Your JavaScript function was wrapped in a window.load handler putting it in the wrong scope. Just putting it in the head will suffice.
Your button had the type button, not submit. The onclick="form.submit();" in your button was running and submitting the form since it was triggering the submission, instead of triggering the form's submit handler (onsubmit="return go_search();"). Changing the button's type from button to submit will fix that.
jsFiddle example
You need to lose the onSubmit tag. Just returning it FALSE won't exactly acheive what you are going for. It seems you want to call a function that MAY return "false" if validation fails. Here is a good method for handling that.
You need to attach the function call to your submit button
onclick="go_search()"
And inside your function, make the form submit if you'd like (after validation).
function go_search(){
alert('abort');
if (youWantToSubmit==true) {
form.submit();
}
}
Even this won't work 100% because your form has no name or ID. You need to add those, and use a more correct call like:
document.getElementByID("[formID]").submit();
you can do this with jquery
$("#searchButton2").click(function(e){
e.preventDefault();
alert('abort');
});
JSFIDDLE
Use jquery.
$(function(){
$('form.search').submit(function(){
return false;
});
});
See here: http://jsfiddle.net/U6UC3/
Below is a code of a simple html form and javascript code for checking if the fields are empty or not, when user clicks the submit button.
The problem is, that the form is submitted, even if the necessary fields are not filled in.
As you can see, I am just a beginner with JS coding, so I don't know, if the problem is in if/else statements, somewhere else in the JS code or if the form is not set up properly.
<script>
function preveri(pov){
var preveriime = pov.ime.value;
var preverirojstvo = pov.rojstvo.value;
var preverimail = pov.email.value;
var preverikategorijo = pov.kategorija.value;
if (preveriime == "") {
document.getElementById('imeA').style.display="block";
}
if (preverirojstvo == "") {
document.getElementById('datumA').style.display="block";
}
if (preverimail == "") {
document.getElementById('emailA').style.display="block";
}
if (preverikategorijo == "") {
document.getElementById('kategorijaA').style.display="block";
}
if(preveriime != "" && preverirojstvo != "" && preverimail != "" && preverikategorijo != ""){
document.pov.submit();
}
else{
return false;
}
}
</script>
<h4>OBRAZEC ZA SPLETNE PRIJAVE</h4>
<br/>
<form name="pov" method="POST" action="thankUPage.php">
<input name="ime" type="text" placeholder="Ime in Priimek"></input>
<input name="rojstvo" type="text" placeholder="Datum rojstva"></input>
<input name="email" type="text" placeholder="E-pošta"></input>
<input name="kategorija" type="text" placeholder="Kategorija"></input>
<textarea name="povprasaj" placeholder="Povprašaj"></textarea>
<input type="submit" name="submit" id="submit" value="Pošlji!" onclick="preveri(pov)" />
</form>
<div id="imeA" class="imeA">Obvezno polje!</div>
<div id="datumA" class="datumA">Obvezno polje!</div>
<div id="emailA" class="emailA">Obvezno polje!</div>
<div id="kategorijaA" class="kategorijaA">Obvezno polje!</div>
</div>
Tnx in advance!
You're returning false on the click event. You need to bind your callback function to the form's submit event, so returning false will cancel the form's submission.
Pressing "enter" while in a form field will submit the form and might not trigger the click event on the submit button.
<form name="pov" method="POST" action="thankUPage.php" onsubmit="return preveri(this);" >