Query OnSubmit Issue - javascript

I am encountering an error using the query below is the snippet of the code:
$('form[action="/home/service/"]').on("click", (function(event) {
if ($("#id1").val() == "" && $("#id2").val() == "") {
alert("Invalid entry");
event.preventDefault();
} else {
$('form[action="home/service/"]').submit();
}
});
the event.preventDefault(); works as it should however its the submit. I have tried using the .off("click" , function); but this didn't work and was the same issue.
Once the preventDefault() method is fired I am unable to resubmit the form once the issues have been resolved? I have seen a few people encounter this but their fixes didn't resolve my issues.
UPDATE
this is what I have now, however I am still receiving the issue, The issue is that it works on the initial on submit however as soon as I try to resubmit with the values it appears that the submit button is locked, has anyone encountered this before? Below is my updated code:
//function on
function checkForm(event)
{
debugger;
if ($("ID1, ID2" ).val() != "" ){
return;
}
else{
event.preventDefault();
$("#alerts-row").html("<div class='alert_box red'><p>Please Ensure that you have filled in at least one item number below!</p></div>");
$('form[action="Form"]').unbind("submit", checkForm);
}
}
$('form[action="form"]').on("submit", checkForm);
Thanks,
Gavey

try putting it before the if statement
$('form[action="/home/service/"]').on("click", (function(event) {
event.preventDefault();
if ($("#id1").val() == "" && $("#id2").val() == "") {
alert("Invalid entry");
} else {
$('form[action="home/service/"]').submit();
}
});

I think that the proper way would be to use the Submit event. If you do that, then on failure to validate you would preventDefault (as you have done), and on success you wouldn't prevent the default.
There's nothing stopping you having a click event on some element that simply calls form.submit(), but you should probably consider using a <Button> instead that can submit automatically.

To resolve the issue which I was having we used unobtrusive Validation, with the help of some samples we were able to create the or statement and allowed us to post the correct validation on the form.
$(document).ready(function(){
// Register new validation adapter
$.validator.unobtrusive.adapters.addBool('minimumselect');
// Add validator to controls
$input = $("#Input1");
$input.attr('data-val', 'true');
$input.attr('data-val-minimumselect', 'Please provide either this or Number 2');
$input2 = $("Input2");
$input2.attr('data-val', 'true');
$input2.attr('data-val-minimumselect', 'please provide this or Ref Number 1');
// Refresh form - needed to pick up new validator
refreshFormValidators();
});
Thanks,
Richard

Related

Yii2 validate an ActiveForm with javascript

I have a working Active Form, which can be submitted, and validated via Yii PHP. However, I would like to determine if the form is valid, when clicking a Next button.
I can pass error messages to the user via this:
$("#form").yiiActiveForm("validate", true);
But this function doesn't return anything; I don't know if there are indeed any errors or not. I tried this:
$error_count = document.getElementsByClassName("help-block").length
but this does not work; the errors are counted before the UI has updated. If I press the button again, a second time, then error_count is what I'd expect.
This doesn't seem to do anything:
$("#form").yiiActiveForm("validate");
I also tried this:
$('#form').on('afterValidate', function (event, messages, errorAttributes) {}
But this is only triggered after the fact so I'm not sure what to do.
Any advice would be appreciated.
If you need to react to button you simply need to combine both events:
let isNextClicked = false;
$('.next-btn').on('click', function(e) {
e.preventDefault();
isNextClicked = true;
$("#form").yiiActiveForm("validate", true);
});
$('#form').on('afterValidate', function(event, messages, errorAttributes) {
if (!isNextClicked) {
//validation wasn't triggered by clicking next
return;
}
// reset the state
isNextClicked = false;
if (errorAttributes.length > 0) {
//there are errors so we won't let user to continue
//we can also show some alert() here
return;
}
// ... code to show the next tab of form ...
});

jquery dirrty form set it clean manually

I am using jquery dirrty plugin to check the state of a form and prevent it from reloading if there are some unsaved changes.
Link to jquery.dirrty github
Flow:
1) I have initialized jquery.dirty as follows
$(function(){
initializeDirtyForm();
})
/** dirty form initialization*/
function initializeDirtyForm(){
$("#uAForm").dirrty().on("dirty", function(){
$("#uAFormSubmit").removeAttr("disabled");
}).on("clean", function(){
$("#uAFormSubmit").attr("disabled", "disabled");
});
}
2) There is a table on the page and when it click on the td cells it make an ajax call.
function ajaxCallEdit()
{
var result = checkDirtyStatus();
if(result === false) {
return;
}
$.ajax({
....
....
....
....
success:function(){
initializeDirtyForm();
}
)}
}
/** check if the form is dirty */
function checkDirtyStatus(){
dirtyStatus = $("#uAForm").dirrty("isDirty");
if(dirtyStatus == true){
if (confirm("Changes you made may not be saved. Do you still want to reload?")) {
return true;
}else{
return false;
}
}
}
If the form is dirty, it works totally fine and show warning message.
ISSUE
Here is the main issue, if I force it to reload, (this means it won't actually reload page, instead it would make an ajax call) it is still setting the status of the form as dirty. I have tried by re-initializing the jquery form but still the form is flagged as dirty.
To make it extra sure and actually what is the the status of the form, I checked the status and tried to console log on ajaxSuccess.
....
success: function(){
initializeDirtyForm();
var result = checkDirtyStatus();
console.log(result);
}
...
However, consoling this result showing the value as undefined.
I could not find any documentation related to the setting it manually and reinitalizing is not working as intented.
So, if you are javascript wizard could you please check the jquery.dirrty.js file attached above and check if I could trigger following part from the js file or any other hacks that helps me to solve the problem.
setClean: function(){
this.isDirty = false;
this.history[0] = this.history[1];
this.history[1] = "clean";
}
If you need any further details please let me know.
try $("#uAForm").dirrty("setClean");
I just got into needing to do the same thing and that worked for me.
Cheers

An error on a form submit allows the submission

I have a form defined in HTML which can be submitted with a submit button.
I also have a jquery handler in which there is a logger on a non existing object.
$("#myform").submit(function() {
console.log(nosuchobject);
return false;
});
With the logger in place, the form is submitted and the browser changes page. But without the logger, the form is not submitted.
My guess is that when there is an error in the logger the returned value is not false. But is it true ? And how come an error allows for a form to be submitted anyway ?
In your logger code you have print a variable instead of string. just update you code with following
$("#myform").submit(function() {
console.log('nosuchobject');
return false;
});
Use preventDefault for preventing form submition:
$("#myform").submit(function(e) {
e.preventDefault();
});
if you get a js error in the submit function the code after the error won't be executed what means that it does not return a false. You can prevent the form submission at the start of your function like this:
$("#myform").submit(function(event) {
event.preventDefault();
// it does not matter if there is an error now.
console.log(nosuchobject);
});
You should still write your code so it runs without errors.

Store result of JS function in variable when function is run first time - Google Tag Manager

I'm trying to create a custom JavaScript variable for Google Tag Manager, and I can't seem to get the functions to run in the right order...
(As seen below:)
This is a chunk of code that was created to check whether an email form was filled out correctly or not. ValidateForm() is run when the user has entered their name and email address, and hit the 'send' button (the function EmailCheck checks whether the email address is valid or not). ValidateForm will then return either true or false. When ValidateForm evaluates to true AND the user has hit the 'send' button, I want to send an event to Google Analytics.
My approach has been to try and store the result of ValidateForm in a variable when it's run the first time, so that my additional anonymous function will evaluate to true, but I can't seem to get the syntax right and now I'm doubting this is even possible (?).
My other idea was to just run the anonymous function on onload, but that will never evaluate to true since ValidateForm is not run until the user has entered their details and hit the 'send' button... How do I make this right? Any help appreciated :)
function ValidateForm() {
var emailID = document.cpren.email
if ((emailID.value == null) || (emailID.value == '')) {
alert('Please enter a valid email address')
emailID.focus()
return false;
}
if (EmailCheck(emailID.value) == false) {
emailID.value = ""
emailID.focus()
return false;
}
return true;
}
//anonymous function
function () {
var result = //the result of ValidateForm when it was run when user hit the 'send' button
if (result) {
return = "checkedOutTrue"
} }
From your question, I think you essentially want to validate your form. To do this part I would just use a standard Custom HTML tag which is fired on page load (DOM ready probably). If you want to be able to fire certain tags when a valid (or invalid) form is submitted, then you should push custom events on to the dataLayer as appropriate.
You probably want to do the following, create a new custom HTML tag with the following code. This code will bind a function to the 'submit' event of your form:
$('#myform').on('submit', function(){
function ValidateForm(){
var emailID = document.cpren.email;
if ((emailID.value == null) || (emailID.value == '') || EmailCheck(emailID.value) == false) {
alert('Please enter a valid email address');
emailID.focus();
dataLayer.push({'event':'form-submitted', 'status':'fail', 'error':'invalid email'});
return false;
}else{
dataLayer.push({'event':'form-submitted', 'status':'success'});
return true;
}
}
});
With this code, you always get a custom event in the dataLayer to tell you when a form has been submitted and you then have dataLayer items to tell you the status of the submission and an error code if it's failed.
You can then build a trigger to fire off of the form-submitted event and populate variables to understand the status and then fire tags accordingly.
The problem I am finding with custom javascript variables in GTM is that they are executed at all phases during the page load. Not just on the triggers where you want them to be executed and the order that they are executed cannot even be set.
So I think you will need to re-evaluate your approach.

Trying to validate results after doing an ajax call

Alright so i have form validation function.the function runs through form validation functions that returns false if the field isn't valid.
The problem is when it get to the function that uses ajax to check if the field is valid.
for some reason its seems that it doesn't "wait" for ajax to return and returns false automatically.
is there a way around this?
Here is the code:
function form_validation(){
if (!NewValidationForm('pcode', 'Please fill in all the fields'))
return false;
if (!NewValidationForm('fname', 'Please fill in all the fields'))
return false;
if(!validate_coupon()){
alert("bad!!");
return false;
}
return true;
}
function validate_coupon(){
var url = $j("#site_url").val() + 'ajax_functions.php';
var coupon = $j("#pcode").val();
var result_status = false; // seem its jumps from here to:
$j.ajax({
type: "POST",
url: url,
data: { ajax: 'ajax', coupon: coupon}
}).success(function(insertID){
var obj = $j.parseJSON(insertID);
if(obj.status == 1){
result_status = true;
}
});
// straight over here
if(result_status == true){
return true;
}
}
Usually in this situation I do something like this in $(document).ready():
$('form').submit(function (evt) {
if (!$(this).attr('data-submitted')) {
evt.preventDefault();
$(this).attr('data-submitted', 'true');
// call your form validation code here that fires the ajax request
return false;
}
return true;
});
Then, in your $.ajax callback, when your validation completes, call $('form').submit(). This effectively uses an attribute on the form as a flag for whether the state of the validation request. When the user first submits the form, the flag gets set and the validation process begins. When the validation completes, the form's submit event is triggered, and since the flag is set, this time the form gets submitted like normal.
If this approach works for you, you'll probably want to add a little polish. For example, you'll probably want to disable the submit button before calling $.ajax and enable it again if the validation fails. You'll also probably want to remove the data-submitted attribute from the form if the validation fails, since the user might submit the form a second time and you presumably want to perform another validation in that case.

Categories

Resources