Form is submitting even if validation fails - javascript

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);" >

Related

Form Submit with JS Not Posting to Controller

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.

How to get the input type submit ID and apply javascript

I am using below jsp' form to submit the data. Before submitting I want to apply javascript.
<form name="inventory" method="post" action="<%=request.getContextPath() %>/Tdata_Main" class="form-light mt-20" role="form" onsubmit="return validate(this)">
Now, I have three input tags of 'Submit' type
<input type="submit" name="submit" class="btn btn-two" value="Update Inventory">
<input type="submit" name="submit" class="btn btn-two" value="Add Empty Row">
<input type="submit" id="submitDelete" name="submit" class="btn btn-two" value="Delete Row">
After adding three new columns and filling in the data one by one, I added forth one as shown below. Now, I am in no need of this forth empty row hence I want to delete it. But the javascript code is getting applied here too and asking me to fill in the blank fields.
Below is the javascript code that is getting executed on the onSubmit event initiated from form.
<script type="text/javascript">
function validate(form) {
//alert(form.id);
if(form.id != "submitDelete"){ // NOT WORKING
for(var i = 0; i < form.elements.length; i++){
if(form.elements[i].type == "text"){
if(form.elements[i].value.length == 0 || form.elements[i].value.length == "null"){
alert('No value entered in '+form.elements[i].name+'.');
form.elements[i].focus();
return false;
}
}
}
}
if (confirm("Would you like to proceed!") == true) {
return true;
}
else{
return false;
}
}
</script>
How could I avoid getting this javascript code being applied on Delete using Javascript. Kindly suggest.
Your code works fine. Only one thing you should remove the action attribute from your form element and post that data using javascript only.
Also your delete button is disabled. Enable it and it will work fine

How do I allow form submission with the submit button and the enter key?

I want the user to be able to submit a form by clicking the submit button or the enter key. I'm using jQuery and here's my code:
<input id="weather"/>
<button id="myButton" type="text">Response</button>
</div>
<script type="text/JavaScript">
$("#myButton").keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
$("#myButton").submit();
}
});
document.getElementById("myButton").onclick = function() {
if (document.getElementById("weather").value.toLowerCase() != "nice" && document.getElementById("weather").value.toLowerCase() != "crappy") {
alert("Please enter only either 'Nice' or 'Crappy.'");
} else if (document.getElementById("weather").value.toLowerCase() == "nice") {
alert("GREAT! Let's go the the BEACH!!");
} else {
alert("Hmm. That blows. Well then, I just won't be going outside today.")
}
};
</script>
Wrap the whole thing in a form tag and change the button type to submit. Enter will then submit the form.
<form>
<input id="weather"/>
<button id="myButton" type="submit">Response</button>
</form>
JSFiddle
<input type="text" id="weather" />
<input type="button" id="myButton" value="Response"/>
The onclick script should be
document.getElementById("myButton").onclick(function(){
if (document.getElementById("weather").value.toLowerCase() !="nice" && document.getElementById("weather").value.toLowerCase() !="crappy") {
alert("Please enter only either 'Nice' or 'Crappy.'");
}
else if (document.getElementById("weather").value.toLowerCase() =="nice"){
alert("GREAT! Let's go the the BEACH!!");
} else {
alert("Hmm. That blows. Well then, I just won't be going outside today.")
}
});
You should use submit type of button. It should not be a text type.
Best way is to wrap input and button with form and check input only in case of form submit like:
$(function() {
$("#weatherForm").submit(function(event) {
event.preventDefault();
var $weatherElement = $('#weather');
if ($weatherElement.val() != "Nice" && $weatherElement.val() != "Crappy") {
alert("Please enter only either 'Nice' or 'Crappy.'");
} else if ($weatherElement.val() == "Nice") {
alert("GREAT! Let's go the the BEACH!!");
} else {
alert("Hmm. That blows. Well then, I just won't be going outside today.")
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" id="weatherForm">
<input id="weather" name="weather" />
<input type="submit" id="myButton" value="Response" />
</form>

Onsubmit still submits when returning false

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.

Error Message will not show in JQuery if it is NOT the first one encountered

I have a feedback form and I am replicating some code to check for values in text inputs and textareas. I have a name field and a feedback field. The errors hide on document load and at the start of a click function The name one shows as expected, but I cannot get the feedback one to show.
I set the errors to show on document load but hide onclick and I could get the feedback error to show if I filled in the name(the name error would hide, as expected).
HTML form.
<div class="slide-out-div">
<h3>Give us Feedback</h3>
<a class="handle" href="#">Content</a>
<p>We would love to hear your ideas to make the site more user-friendly or efficient for your benefit.</p>
<form name="feedbackform" id="feedbackform" action="" method="post">
<label for="feedname">Name:</label>
<input type="text" name="feedname" id="feedname" style="width:100%" /><br />
<label class="error" for="feedname" id="feedname_error">Please insert your name.</label> <br />
<label for="feedback">Feedback:</label><br />
<textarea name="feedback" id="feedback" style="width:100%;height:150px;"></textarea>
<label class="error" for="feedback" id="feedback_error">Please insert your some feedback.</label> <br />
<input type="submit" value="Submit Feedback" id="feedbacksubmit" />
</form>
<div id="feedwrap"></div>
</div>
JQuery Process
$('#feedbacksubmit').click(function (e) {
$('.error').hide();
//Cancel the link behavior
e.preventDefault();
var name = $("input#feedname").val();
if(name == ""){
$("label#feedname_error").show();
$("input#feedname").focus();
return false;
}
Var feedback = $("textarea#feedback").val();
if(feedback == ""){
$("label#feedback_error").show();
$("textarea#feedback").focus();
return false;
}
//process
return false;
});
Any help would be greatly appreciated.
It's becasue you are returning false as soon as you complete the validation of the name. That'll stop the execution of the function there and the second error message will not show up. May be you can write something like this.
$('#feedbacksubmit').click(function (e) {
$('.error').hide();
//Cancel the link behavior
e.preventDefault();
var returnvalue = true;
var name = $("input#feedname").val();
if(name == ""){
$("label#feedname_error").show();
$("input#feedname").focus();
returnvalue = false;
}
var feedback = $("textarea#feedback").val();
if(feedback == ""){
$("label#feedback_error").show();
$("textarea#feedback").focus();
returnvalue = false;
}
//process
return returnvalue ;
});
It appears that if I move the error above the textarea is shows but otherwise it does not, it must show but not visible to the user.

Categories