I have some very old javascript code on an existing site and I wanted to update it, but I'm running into errors and I'm not sure what to replace it with. The code is just part of a section where it does a .submit() call to the form. Then the code reaches the try condition, it throws the error that livequery is not a function. Code is also below the screenshot.
Also I'm not sure if the "var form" is outside the scope of the try for form to work or not. What could I have wrong here?
var submit = false;
var form = $("#webform-client-form-2")[0];
try {
if (repair) {
console.log('repair is true - line 317');
$(".simple-dialog").click();
$(".ui-dialog, .ui-widget-overlay").hide();
$(".form-actions").livequery(function() {
console.log('livequery - line 321');
$("#edit-submitted-name").val(subject_field);
$("#edit-submitted-phone").val(phone);
$("#edit-submitted-email").val(email);
$("#edit-submitted-details-of-issue").val(problem);
var find = $(".form-actions")[0]; //get the 1st form actions on the page. if more than 2 forms on page, this might submit wrong form.
if (!submit && find) {
console.log('repair is true - line 328');
submit = true;
$("#webform-client-form-2").submit();
$(".form-actions").expire();
return false;
}
});
} else if (contact) {
console.log('yyy');
console.log(form);
$("#edit-submitted-phone-number").val(phone);
$("#edit-submitted-message").val(problem);
$(form).submit();
} else {
console.log('zzz');
$(form).submit();
}
} catch (error) {
console.log(error);
console.log("no form - line 346");
}
Related
To make an evaluation on the last page of a portal, using the submit button, Microsoft provides an extension for the function "webFormClientValidate" that the submit button should trigger:
https://learn.microsoft.com/en-us/dynamics365/customer-engagement/portals/add-custom-javascript.
I put this code in my last step in the portal:
console.log("alive");
if (window.jQuery) {
console.log("1");
(function ($) {
console.log("2");
if (typeof (webFormClientValidate) != 'undefined') {
console.log("3");
var originalValidationFunction = webFormClientValidate;
if (originalValidationFunction && typeof (originalValidationFunction) == "function")
{
console.log("4");
webFormClientValidate = function()
{
console.log("5");
originalValidationFunction.apply(this, arguments);
console.log("6");
// do your custom validation here
if (...)
{
console.log("7 false");
return false;
}
// return false;
// to prevent the form submit you need to return false
// end custom validation.
return true;
};
}
}
}(window.jQuery));
}
On pageload the log writes out:
alive
1
2
3
4
Pressing the submit button should trigger the "webFormClientValidate" function, but nothing happens. "5" is not being written to the log. Anyone know why?
Update: From debugging it appears as if the page does not recognize "webFormClientValidate" at all. Searching through the elements however, this guy appears:
function webFormClientValidate() {
// Custom client side validation. Method is
called by the next/submit button's onclick event.
// Must return true or false. Returning false
will prevent the form from submitting.
return true;
}
My research shows other people just pasting in the same bit of code. Witch tells me that it should work somehow:
http://threads290.rssing.com/chan-5815789/all_p2645.html
https://rajeevpentyala.com/2016/09/12/useful-jscript-syntaxes-adx-portal/
http://livingindynamics365.blogspot.com/2018/02/validating-user-input-in-crm-portals.html
If you are using an Entity Form, use entityFormClientValidate in place of webFormClientValidate
I've spent some time looking around and trying multiple solutions without luck, while attempting to streamline a form to create a pseudo bulk process.
Essentially I simply need to prevent default on a submit button, but to trigger it if several subconditions are met, at least one of which uses an ajax call.
I've tried variations of e.preventDefault, $('#form').submit(false); and I can either get the validation to occur, or the form to submit, but never both in the right places. (for example it will submit without checking for duplicate entries)
Here's a summed up version of what I've been attempting.
This is the main variable which holds the first part of the check:
var verifyValue = function() {
// this stops the form, and then things validate fine.
$('#add-item-form').submit(false);
//but then I need to get it started again to submit valid entries
if($('#value_of_json_array').val().length != 0){
$('#value_of_json_array').prop("readonly", true);
jQuery.getJSON('{{ path('query_to_get_array') }}?' +
$.param({barcode: $('#value_of_json_array').val()}))
.done(checkedValue);
}
};
This is where it is called:
$("#verify-value").click(verifyValue);
Below is a shorthand of the conditional being run:
var checkedValue = function(items) {
if(items.length == 0){
// success conditions
}
else {
//this was just one attempt
$('#form').submit(false);
if( /* sub condition of data passed from JSON array */){
//condition creates new form which upon action sends AJAX call
}
else
{
//second error condition
}
}
};
What I'm trying to do is to have if any of the subconditions occur, to have it stop the submit button (e.g. preventDefault behavior) and if it does not have any of these, to allow the submission of the form
It feels like it should be simple, however no matter where I do this, including using $(this).unbind('submit').submit() It doesn't work right.
Either the validation occurs correctly and nothing submits, or everything submits even if it's not supposed to.
I feel like modifying var verifyValue will work but I'm not sure how to get the conditional statements bound into an event.
Edit:
Okay, so I was guilty of seriously overthinking this issue, and came up with a solution which I will put below (in case anyone is interested)
Since your validation includes an async step, it'd be easier to just stop the form submission right away.
Then call your validation function, which will set the validation state of the form in a "global" state (maybe just a closure of the event handler). If the validation is fine, submit the form, else just show the validation error.
// You'll need to reset this if an input changes
var isFormValid = false;
$("#form").on('submit', function(e) {
if (isFormValid) {
return true;
}
e.preventDefault();
validateForm(function(valid) {
if (valid) {
isFormValid = true;
$('#form').submit();
}
});
});
function validateForm(cb) {
var form = $('#form');
// do some synchronous validations on the form inputs.
// then do the async validation
if($('#value_of_json_array').val().length != 0){
$('#value_of_json_array').prop("readonly", true);
jQuery
.getJSON(
'{{ path('query_to_get_array') }}?' +
$.param({barcode: $('#value_of_json_array').val()})
)
.done(function(result) {
if (checkedValue(result)) {
cb(true);
} else {
cb(false);
}
});
} else {
cb(false);
}
}
How about this approach, here's a simple skeleton:
$('#form').submit(function(e){
var formError = false;
// set formError to true if any of the checks are not met.
if(some condition) {
// do a conditional check
formError = true;
} else if(another condition) {
// do another conditional check
formError = true;
}
if(formError) { // stop form submission of any of the conditions are not met.
return false; // same as e.preventDefault and e.stopPropagate()
}
});
It turned out I was seriously overthinking this issue. It was a lot easier to handle by binding everything into a button that was not a submit, and if it passed the validation simply use a submit condition. This way I didn't need to worry about preventing default behavior and turning it back on again (which was where I was getting stuck). Since regular buttons have no default behavior, there was no need to be concerned about it submitting incorrectly.
The original function just needed to be simplified to:
var verifyValue = function() {
if($('#value_of_json_array').val().length != 0){
$('#value_of_json_array').prop("readonly", true);
$('#barcode-buttons').hide();
jQuery.getJSON('{{ path('query_to_get_array') }}?' +
$.param({barcode: $('#value_of_json_array').val()}))
.done(checkedValue);
}
};
$("#verify-value").click(verifyValue);
and then the check only needed to do this
var checkedValue = function(items) {
if(items.length == 0){
$('#form').submit()
}
else {
//error conditions
}
};
Working on form validation in jQuery. All of my validations seem to be working correctly.
See JSFiddle here.
If you submit the form with no data, all of the correct errors appear.
If you fix one of the fields, the error message for that field does not clear.
I think it probably is something wrong with my logic, but unsure if there is an easy way to try and check the validation again?
My code for submit in jQuery is here. The first four validate functions are checking for errors and displaying errors if there are any. If there are any errors with anything, the form is prevented from submitting. If there is no error, an alert is displayed and the submission is allowed. I know that the problem is that after that first if statement finds an error - there is no way to look and see if the error is fixed and to clear that error. So I'm stumped on where to go with this - would it be better off in a loop maybe?
// On Form Submission Validate Form
$("#contact_submit button").click(function(event){
error_name = validateName();
error_email = validateEmail();
error_activity = validateActivities();
isCreditIssue = validateCredit();
event.preventDefault();
var valid = true;
if ((error_name) || (error_email) || (error_activity) || (isCreditIssue)){
console.log("errors");
valid = false;
} else {
alert('GREAT! form completed');
valid = true;
}
if (valid) {
return;
}
You left out hide statements when the form values become valid at many places. Just an example (inside validateZip):
if ((!errorZip)||(zip!= 5)){
$(".error_zip").show();
errorZip = true;
console.log('zip issue');
} else {
errorZip = false;
}
You should replace it with this:
if ((!errorZip)||(zip!= 5)){
$(".error_zip").show();
errorZip = true;
console.log('zip issue');
} else {
$(".error_zip").hide();
errorZip = false;
}
I'm working on a project where I have some error checking. However, the form wanted to submit each time so I had to break the submit. Here is what I did.
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "order-form" }))
{
...
<input type="submit" name="btnSaveOpv#(item.Id)" value="#T("Admin.Common.Save")" id="btnSaveOpv#(item.Id)" class="adminButton" style="display: none;" onclick="SaveBtn(#item.Id);" />
...
var originalIssuedQty = 0;
function SaveBtn(id) {
var quantity = parseInt($("#pvQuantity" + id).val());
var issuedQty = parseInt($("#pvIssuedQty" + id).val());
var stockQty = parseInt($("#hfStockQty" + id).val());
var availableStockQty = stockQty + parseInt(originalIssuedQty);
//Issued Quantity cannot exceed Quantity (you can't issue more than requested)
if (issuedQty > quantity) {
alert("Issued Quantity cannot exceed Quantity.");
$("#order-form").submit(function (e) { e.preventDefault(); });
return false;
}
//Make sure Issued Quantity is within Available Stock Quantity
if (issuedQty > availableStockQty) {
alert("There is not enough Products in Stock to issue this amount.");
$("#order-form").submit(function (e) { e.preventDefault(); });
return false;
}
//Present confirmation
var result = confirm('#T("Admin.Common.AreYouSure")');
if (!result) {
$("#order-form").submit(function (e) { e.preventDefault(); });
return false;
}
else {
$("#order-form").submit(function (e) { this.submit(); });
//$("#order-form").submit(function (e) { return true; });
}
}
...
}
Here is the problem. Whenever I try to submit the first time without triggering any of my error checking, things work. When I trigger the error checking, things work. However, if I fix the error and try to submit again, the page merely refreshes. Any ideas on this would be very helpful. Thanks.
You are making things too complicated.
This is a basic template on how you do validation and how you stop the form from submitting when it's not valid:
$(function() {
$("#order-form").submit(function (e) {
var isValid = false;
// Do your validation here and put the result in the variable isValid
if ( !isValid ) {
e.preventDefault(); // If the form is invalid stop the submit, otherwise proceed
}
});
});
Every time you call $("#order-form").submit(function (e) { whatever });, you add an additional handler function. It doesn't remove the handlers you've already added. This is probably why it breaks.
Repeatedly changing the submit event handler is a messy way to do it. Instead, you should have a single function which handles the submit event, and that function should do (or call) the error checking, and preventDefault() if necessary (like ZippyV is suggesting).
I have a function which verifies if some fields have been filled out (if length > 0) before submitting. If it fails to submit, I don't want to redirect the client at all. Right now, I have the following:
function onSubmit()
{
if (verify()) //This function will throw alert statements automatically
{
document.getElementById('my_form').submit();
return void(0);
}
else
{
document.getElementById('my_form').action = null;
}
}
However, it doesn't matter if verify() returns true or not, I still redirect the client and wipe her inputted fields. How do I keep the client on the page if a required field is blank? (I don't want to lose her currently filled out form...)
Also, I can't use the slick JQuery libraries, since it's not supported on some older browsers. (I'm trying to capture the most general audience.)
This is how I would try to solve this:
document.getElementById('my_form').onsubmit = function( e ){
var event = e || window.event;
// function payload goes here.
event.returnValue = false;
if ( event.preventDefault ){ event.preventDefault(); }
return false;
}
Can be used with event delegation too.
return false to the form!
<form onsubmit="return onSubmit()">
function onSubmit()
{
if (verify()) //This function will throw alert statements automatically
{
return true;
}
else
{
return false;
}
}
to stop the form from submitting, return false from your onSubmit