Block form submit JS not working - javascript

I want to check some forms values before submit it. So I put this into my :
<form name="frmcontact" id="frmcontact" method="post" action="<?php echo($action);?>" class="forms" onsubmit="return checkContactsFields()">
And here is my JS function :
function checkContactsFields(){
var newIdValue = document.forms["frmcontact"]["new_id"].value;
if(newIdValue !== 'ADRESSE NON IDENTIFIE'){
var form = document.forms["frmcontact"].elements;
for(var i = 0; i < form.length; i++) {
if(form[i].name === 'street' || form[i].name === 'cp' || form[i].name === 'town'){
if(form[i].value === ''){
console.log('ok');
document.getElementById('main_error_popup').style.display = 'table-cell';
if(form[i].name === 'street')
errorMsg = 'Voie';
else if(form[i].name === 'cp'){
errorMsg = 'Code Postal';
}else{
errorMsg = 'Ville'
}
document.getElementById('main_error_popup').innerHTML = 'Le champ ' + errorMsg + ' est vide';
return false;
}
}
}
return true;
}
return true;
}
The problem I have is that even with the return false statement, the form is submit..
Any idea of the reason ?
Thanks in advance

Add preventDefault to the function & submit the form using ajax
In html
onsubmit="return checkContactsFields(event)"
in js
function checkContactsFields(e){
e.preventDefault()
}

A quick test in chrome seems to work if I
just do :
function checkContactsFields(){
alert("I won't submit");
return false;
}
https://plnkr.co/edit/yA3hVlDtfUGxSCceqPMY?p=preview
If your javascript throws an error during execution the submit will still happen.
What does your html look like?

Related

Unable to redirect to page using window.location

I'm not able to redirect to a single page using windows location in .js page.
However I checked with alert box to see whether the condition is passing true or not and it is working while location is not working.
var attempt = 3; // Variable to count number of attempts.
// Below function Executes on click of login button.
function validate() {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
if (email == "test1#gmail.com" && password == "test1") {
alert("Login successfully");
window.location.href = 'messages.php';
return false;
} else {
attempt--; // Decrementing by one.
alert("You have left " + attempt + " attempt;");
// Disabling fields after 3 attempts.
if (attempt == 0) {
document.getElementById("email").disabled = true;
document.getElementById("password").disabled = true;
document.getElementById("submit").disabled = true;
return false;
}
}
}
I feel I'm missing something.
I suspect you're calling validate like this:
<form onsubmit="validate()" ...>
That won't use the return value of validate to cancel the submit. You need a return:
<form onsubmit="return validate()" ...>
Since the submission is not being cancelled, the form submission is a navigation action, which overrides your assignment to window.location.href.
In a comment you've said you're doing this:
<button type="submit" name="submit" onclick="validate()" class="btn-secondary">Sign In</button>
If so, adding the return to the onclick should fix it on any modern browser:
<button type="submit" name="submit" onclick="return validate()" class="btn-secondary">Sign In</button>
But I would move it to an onsubmit on the form instead.
Side note: There's no need for the type="submit" on that button. submit is the default type for button elements.
var attempt = 3; // Variable to count number of attempts.
// Below function Executes on click of login button.
function validate() {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
if (email == "test1#gmail.com" && password == "test1") {
alert("Login successfully");
window.location.href = 'messages.php';
return false;
} else {
attempt--; // Decrementing by one.
alert("You have left " + attempt + " attempt;");
// Disabling fields after 3 attempts.
if (attempt == 0) {
document.getElementById("email").disabled = true;
document.getElementById("password").disabled = true;
document.getElementById("submit").disabled = true;
}
return false; // ALWAYS return this. else it will proceed with page submit.
}
}

Mvc validation and loader

In form post method in MVC view,
if validation fires then loader should not come and display only validations
else no validations fire then loader should come and save the data.
What I have tried:
placed loader on form submit in javascript and disable the button.
$("#frmContact").submit(function (e) {
$(".loading").css("display", "inline");
});
1) loader : Issue is that if validation fires, then loader also come alongwith validations and then need to reload the page and input data.
2) Disable Submit button : If I disable the Submit button on click and if validation fire then after button remains the disable instead enable. So if validation is there then enable the button and if validations are not fire then disable the button.
All this to avoid the duplicate entry as if button enables then if user clicks on submit.
You can do it this way
HTML :
<div id="ajax-loader" style="display:none;">
<img src="<?php echo $loaderSrc; ?>" style="height: 200px;width: 200px;">
</div>
<input type="submit" id = "btnSubmit" value="Submit" name="yt0" onclick="return validateForm();">
In script : (here you can change the fields...i am showing one of my example)
var error_flag = true;
var error_required = true;
$('#btnSubmit').click(function(e){
e.preventDefault();
if(error_flag && error_required){
$("#ajax-loader").css("display", "block");
$('form#login-form').submit();
}
});
function validateForm(){
var user_pass = document.getElementById('LoginForm[user_pass]').value;
var dob = document.getElementById('LoginForm_dob').value;
var re_pass = document.getElementById('re_pass').value;
var user_name = document.getElementById('LoginForm[user_name]').value;
var email = document.getElementById('LoginForm[email]').value;
var tnc = document.getElementById('checkbox1').checked;
// alert(tnc);
var filter=/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
if(user_name == ''){
validate('LoginForm[user_name]','Nick name is required.');
}else if(email == ''){
removeerror('LoginForm[user_name]');
validate('LoginForm[email]','Email is required.');
}else if(!filter.test(email)){
removeerror('LoginForm[email]');
validate('LoginForm[email]','Please enter valid email.');
}else if(user_pass == ''){
// removeerror('LoginForm[email]');
validate('LoginForm[user_pass]','Password is required.');
}else if(user_pass.length < 6){
removeerror('LoginForm[user_pass]');
validate('LoginForm[user_pass]','Min length should be 6.');
}else if(re_pass == ''){
removeerror('LoginForm[user_pass]');
validate('re_pass','Repeat password is required.');
}else if(user_pass != re_pass){
removeerror('re_pass');
validate('re_pass','Password does not match.');
}else if(dob == ''){
removeerror('re_pass');
validate('LoginForm_dob','Dob is required.');
}else{
if(tnc == false){
document.getElementById('tnc_check').innerHTML = 'Please agree Terms and Condition' ;
document.getElementById("tnc_check").style.color = "red";
error_required = false;
}else{
error_required = true;
document.getElementById("tnc_check").style.display = "none";
removeerror('LoginForm_dob');
}
}
}
function validate(id,msg){
document.getElementById(id).style.border='4px solid red';
document.getElementById(id).value = "";
document.getElementById(id).placeholder = msg;
error_required = false;
}
function removeerror(id){
document.getElementById(id).style.border='none';
error_required = true;
}
Check validation on form submit or button submit event using javascript.
if($('#MyForms').valid())
{
// Do something (Valid)
}
else
{
// Do something (invalid)
}
the answer is simple. put valid in the form post event. all is what you want.
$("#frm").submit(function (e) {
if ($(this).valid()) {
$(".loading").css("display", "inline");
}
});

using jquery addclass and removeclass in PHP

I' working on a PHP-Jquery-Ajax submit info form and I would like to use the addclass and removeclass jquery methods but I can't make it work as I want, so my question is: How do I have to fix the code below in order to add a css depending on the user input?
The addclass and removeclass are in the function verificaForm where I validate the input fields, in this case I only show you two fields validations but there are more... I also know that out there is a library(validate.js) that helps to validate the inputs from users but in this specific case I must have to sitck to this code.
here is my js code and thanks in advance:
$(document).ready(function () {
$('#ID_formulario').on('submit', function (e) {
e.preventDefault();
var nombre = $('input#ID_nombre').val().trim();
var email = $('input#ID_email').val().trim();
if (validaForm(nombre, email)) {
$('#result').html("<b>resolviendo peticion...</b>");
var url = $(this).attr('action');
var data = $(this).serializeArray();
var type = $(this).attr('method');
//...more code goes here ... it works fine ...
}
});
});
function validaForm(nombre, email) {
if ((nombre == '') || nombre.replace(/s+/, '') == '') {
alert("Favor especificar nombre");
nombre.addClass('hightlight');
return false;
} else {
else nombre.removeClass('hightlight');
}
if (nombre.length < 4) {
alert('El valor del campo es muy corto');
return false;
}
if ((email == '') || email.replace(/s+/, '') == '') {
alert("Favor especificar correo");
return false;
}
return true;
}
You should pass the element to the function, not the value. Then You can obtain the value within the function. Something like that:
var nombre = $('input#ID_nombre');
var email = $('input#ID_email');
if(validaForm(nombre, email))
....
function validaForm(nombre,email){
var nombre_value = nombre.val().trim();
var email_value = email.val().trim();
.......
So, you can add classes to a jQuery object and not to a value. Change things around like below.
Replace
var nombre = $('input#ID_nombre').val().trim();
var email = $('input#ID_email').val().trim();
if (validaForm(nombre, email)) {
With
if (validaForm($('input#ID_nombre'), $('input#ID_email'))) {
And modify your function as below.
function validaForm(nombre,email) {
var nombreVal = $.trim(nombre.val());
var emailVal = $.trim(email.val());
if ((nombreVal == '') || nombreVal.replace(/s+/, '') == '') {
..........
..........
}
And remove that extra else in here:
} else {
else nombre.removeClass('hightlight');
}
And change it to
} else {
nombre.removeClass('hightlight');
}

jQuery: form not submitting with $('#id').submit();, but will submit with a 'submit' button?

I am facing the problem when i submit the form by input type button here is my code :
<form method="POST" id="eulaForm" action="downloadPack.php?packId=<?php echo $_REQUEST['packId'];?>" enctype="multipart/form-data">
that is my form, which looks fine to me. in that form, i put this button:
<input name="declineBtn" id="declineBtn" value="Decline" type="button" class="back">
<script type="text/javascript">
$(document).ready(function(){
$('#declineBtn').click( function() {
searchTxt = $('#searchText').val();
// ajax logic to test for what you want
if (searchText != '') { return chgAction(searchTxt); } else { return true;}
});
});
function chgAction(cmpText)
{
if(cmpText != '')
{
$('#eulaForm').attr('action', 'searchResult.php');
alert("After - action = "+$("#eulaForm").attr("action"));
//submit the form
$('#eulaForm').submit();
}
else{
url = '<?php
echo basename($_SERVER['HTTP_REFERER']);?>';
window.parent.location.href = url;
//parent.history.back();
return false;
}
}
</script>
and as you can see, it calls $('#eulaForm').submit(); , but the form is not submitting (ie. the page is not refreshing). why is that?
thanks!
try like this:
wrap up chgAction() inside document ready and add preventDefault()
$(document).ready(function(){
$('#declineBtn').click( function(e) {
e.preventDefault();
searchTxt = $('#searchText').val();
// ajax logic to test for what you want
if (searchText != '') { return chgAction(searchTxt); }
else { return true;}
});
function chgAction(cmpText)
{
if(cmpText != '')
{
$('#eulaForm').attr('action', 'searchResult.php');
alert("After - action = "+$("#eulaForm").attr("action"));
//submit the form
$('#eulaForm').submit();
return false;
}
else{
url = '<?php
echo basename($_SERVER['HTTP_REFERER']);?>';
window.parent.location.href = url;
//parent.history.back();
return false;
}
}
});

prevent the user from submitting

I want to prevent the user from submitting data in a form, but when I test it with JavaScript it's not returning true.
this is the submit button :
input type="submit" value="S'inscrire" name="inscrire" onsubmit="return Verifier(this.form);">
and this is the code for the JS test function :
function Verifier()
{
var mdp1 = document.form.mdp.value,
mdp2 = document.form.confirmer.value,
email = document.form.email.value,
pseudo = document.form.pseudo.value;
var testMdpIdentique = (function() {
if(mdp1 == mdp2) return true;
else return false;
})();
if(!testMdpIdentique || mdp1 == "" || mdp2 == "" || email == "" || pseudo== "" )
{
alert ('Il faut remplir tous les champs');
return false;
}
return true;
}
the problem is that it's submitting information even if the test is not valid, I tried to try an alert message in the Valider function but it didn't worked.
In normal Javascript
you can use return value of function to prevent form submission
<form name="myForm" onsubmit="return validateMyForm();">
and function like
<script type="text/javascript">
function validateMyForm()
{
if(check if your conditions are not satisfying)
{
alert("validation failed false");
returnToPreviousPage();
return false;
}
alert("validations passed");
return true;
}
</script>
In jQuery
$('#form').submit(function (evt) {
evt.preventDefault();
window.history.back();
});
In DOJO
dojo.connect(form, "onsubmit", function(evt) {
evt.preventDefault();
window.history.back();
});
I think the below code is syntactically incorrect.
var testMdpIdentique = (function() {
if(mdp1 == mdp2) return true;
else return false;
})();
Replace with
var testMdpIdentique = function() {
if(mdp1 == mdp2) return true;
else return false;
};
Also you don't need to pass (this.form) in the onClick event. Generally submit button submits the form is there is a syntax error in your onClick callback method.

Categories