I have a javascript function that is triggered upon form submission:
var reusecard = true;
var form = document.getElementById('paymentForm');
Worldpay.useOwnForm({
'clientKey': 'xxxxx',
'form': form,
'reusable': reusecard,
'callback': function(status, response) {
document.getElementById('paymentErrors').innerHTML = '';
if (response.error) {
Worldpay.handleError(form, document.getElementById('paymentErrors'), response.error);
$("#paymentErrors").addClass("highlighted_box");
} else {
var token = response.token;
Worldpay.formBuilder(form, 'input', 'hidden', 'token', token);
form.submit();
}
}
});
I want to change the 'reusable' field to false, if the user changes a select box to "NO" on a form, using JQuery.
The ID of the select box is "reuse", which has 2 value choices, "YES" and "NO".
The JQuery I have been trying is:
$(function() {
$( "#reuse" ).change(function() {
if ($("#reuse").val() == "YES") {
reusecard = true;
} else {
reusecard = false;
}
alert (reusecard);
});
});
Whenever the user changes the select box, the Javascript alert works fine, and displays the correct boolean value. However, when the function runs, it always takes the initially set value, and not the changed value.
What am I doing wrong?
Thanks
Related
I am using Checkbox select-all and Deselect all if user not selecting any role alert is showing please select at least one Role.
But the page is Redirecting to Server only reason of this I am getting this error:
Object reference not set to an instance of an object
How can I solve this? Please help me.
This is the code:
$("#selectallchk").hide();
$("#lblselect").hide();
var siteMap = {
detailsFormId: "#site-map-details-form",
onSubmit: function(e) {
siteMap.setRoles();
},
validation: function () {
var validator = $("#site-map-details-form").kendoValidator().data("kendoValidator");
if (!validator.validate()) {
$(".k-invalid:first").focus();
}
var roles = siteMap.setRoles();
$("#site-map-details-form").kendoValidator().data("kendoValidator");
$(".k-invalid:first").focus();
if($('.site-map-access-roles').is(':checked'))
{
return true;
}
else {
alert("Please Select at least One Role."); //not checked
return false;
}
},
setRoles: function() {
var selectedIds = [];
$(".site-map-access-roles:checked").each(function(ind, ele) {
selectedIds.push($(ele).attr("name").trim());
});
$("#AccessRoleIds").val(selectedIds);
if(selectedIds===null)
{
alert("Please Select at least One Rols."); //checked
return false;
}
},
I have a form and I want to show a confirmation massage after clicking submit button and also I don't want to use following method
return confirm("Are You Sure?")
I used JQuery Confirm as following.
#using (#Html.BeginForm("SubmitTest", "HydrostaticReception", FormMethod.Post, new {id="ReceptionForm", onsubmit = "ValidateMyform(this);" }))
{
.....
<button onclick="SubmitMyForm()">Submit</button>
}
The javascript codes are ...
function ValidateMyform(form) {
// get all the inputs within the submitted form
var inputs = form.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
// only validate the inputs that have the required attribute
if (inputs[i].hasAttribute("required")) {
if (inputs[i].value == "") {
// found an empty field that is required
alert("Fill all fields");
return false;
}
}
}
return true;
}
The Javascript code for showing Confirm Box (According JQuery Confirm) is
function SubmitMyForm() {
$.confirm({
title: 'Confirm!',
content: 'Are you sure?',
buttons: {
No: function () {
return true;
},
Yes: function () {
$("#ReceptionForm").submit();
//alert("For Test");
//document.getElementById("ReceptionForm").submit();
}
}
});
}
The Problem IS...
When I click Submit button it doesn't wait for me to click Yes button in Confirm box and the form will submit (the Confirm box appears and after 1 sec disappear and form submits).
But when I use alert("For Test"); instead of $("#ReceptionForm").submit(); , it works correctly. Does anybody knows why I'm facing this problem?!!!
You could use a "flag" to know if the confirmation occured or not to "prevent default" submit behavior.
Remove the inline onsubmit = "ValidateMyform(this);" and use a jQuery event handler instead.
var confirmed = false;
$("#ReceptionForm").on("submit", function(e){
// if confirm == true here
// And if the form is valid...
// the event won't be prevented and the confirm won't show.
if(!confirmed && ValidateMyform($(this)[0]) ){
e.preventDefault();
$.confirm({
title: 'Confirm!',
content: 'Are you sure?',
buttons: {
No: function () {
return;
},
Yes: function () {
confirmed = true;
$("#ReceptionForm").submit();
}
}
});
}
});
I have a webpage that opens a modal form. I validate the modal form using a JQuery function. The problem is that my function is checking all fields in both the modal AND the page behind it.
//validate function
function validateFields() {
var valid = true;
$('.required').each(function () {
if (!$(this).val()) {
addError(this, 'required');
valid = false;
}
});
}
//in my save function
function saveLead(){
if (validateFields()) {
//save
}
}
My validate function is checking all fields with the required class on both my page and modal. How can I get it to just use my page?
UPDATE:
this has complications because my validation function is reused on many pages and is not set up to accept a specific form to check
Is such a thing possible or do I have to do major revisions to the validation or modal in order for this to work?
You could detect the form from which the submit button is clicked. Something like the below should work.
//validate function
function validateFields($submittedForm) {
var valid = true;
$('$submittedForm .required').each(function () {
if (!$(this).val()) {
addError(this, 'required');
valid = false;
}
});
}
//in my save function
// Find the form there 'this' is the submit button
var $submittedForm = $(this).closest('form');
function saveLead($submittedForm){
if (validateFields($submittedForm)) {
//save
}
}
I am using MVC3 and unobstrusive validation. On certain occasions I want to submit a form even if the form is incomplete providing two fields are selected. The JavaScript I am using is as follows:
$('#form_section11').submit(function () {
//event.preventDefault(); //stops form from submitting immediately
var validatorSection11 = $('#form_section11').validate();
if (!$(this).valid()) {
// or family name and date of birth
var FamilyNameExists = true;
var DateOfBirthExists = true;
if (validatorSection11.errorMap["FamilyName"]) { FamilyNameExists = false; }
if (validatorSection11.errorMap["DateOfBirth"]) { DateOfBirthExists = false; }
// show the partial save rules
$('#ParitalSaveIntructions').show();
// show the partial save checkbox
if (FamilyNameExists && DateOfBirthExists) {
$("#AgreePartialSave").show();
if ($("#PartialSave").is(':checked')) {
// partial save has been requested
return true; //// <- save not happening, INCORRECT action
}
// clear perinatalWomanView_PartialSave
$("#PartialSave").removeAttr('checked');
}
return false; // <- save not happening, correct action
}
return true; // <- save happens, correct action
});
The user is presented with a checkbox to confirm incomplete submission. I've indicated where the JavaScript works and where it fails.
I've also added
var validatorSection11 = $('#form_section11').validate(
{
onsubmit: false
}
);
This has no effect. My questions are:
Why is the original return true not functioning?
Am I using the onsubmit: false correctly?
Is there a better way of doing this?
Thanks in advance.
Try using a variable (save) instead of multiple return statements:
$('#form_section11').submit(function (e) {
'use strict';
var self = $(this),
save = false,
FamilyNameExists = true,
DateOfBirthExists = true,
validatorSection11 = self.validate();
if (!self.valid()) {
// or family name and date of birth
FamilyNameExists = true;
DateOfBirthExists = true;
if (validatorSection11.errorMap["FamilyName"]) {
FamilyNameExists = false;
}
if (validatorSection11.errorMap["DateOfBirth"]) {
DateOfBirthExists = false;
}
// show the partial save rules
$('#ParitalSaveIntructions').show(); // should this be "Parital" or "Partial"
// show the partial save checkbox
if (FamilyNameExists && DateOfBirthExists) {
$("#AgreePartialSave").show();
//if ($("#PartialSave").is(':checked')) { // Comment in answer
// // partial save has been requested
// save = true;
//}
save = $("#PartialSave").is(':checked');
// clear perinatalWomanView_PartialSave
$("#PartialSave").removeAttr('checked');
}
//save = false; //This was overriding the `save = true` above.
}
if (!save) {
e.preventDefault(); // stops form from submitting immediately
}
return save;
});
Also, at the section "Comment in answer", this section will likely only execute after the form has been resubmitted because the following would have to happen:
$("#AgreePartialSave").show(); has to execute and show the section.
The user has to put a check in $("#PartialSave") for $("#PartialSave").is(':checked') to return true.
The $('#form_section11').submit() has to fire again for that section of the handler to evaluate.
If there is a different button that the user has to click to do a partial save, you'll likely want to move that whole section into that button handler.
I'm running into issues with the following code:
var setupSearch = {
searchSuggest: function(field) {
$.getJSON('/get-all-journals', {'url':'on'}, function(data) {
var SHCount = Number($.cookie('SHCount'));
var SHArray = new Array();
for (i=1; i <= SHCount; i++) {
SHArray.push($.cookie('SH'+i));
}
$(field).ddautocomplete(removeDuplicate(SHArray), data.response.docs, {
matchContains: true,
max: 5,
cacheLength: 5000,
selectFirst: false,
scroll: false,
formatResult: function(str) { return str; },
formatItem2: function(item) {
return item.journal_display_name;
},
formatMatch2: function(item) {
return item.journal_display_name;
},
formatResult2: function(item) {
return item.journal_display_name;
}
});
});
},
searchForm: function(form) {
var field = form.find('textarea');
// Setup query field for default text behavior
// setupField(field);
setupSearch.searchSuggest(field);
field.autogrow();
field.keydown(function(e) {
if (e.keyCode == 13) {
form.submit();
return false;
}
});
// Make all forms submitting through Advanced Search Form
form.submit(function(e) {
e.preventDefault();
setupSearch.submitSearch(form, field);
});
},
submitSearch: function(form, field) {
if (advancedSearch.checkMinFields() || (!field.hasClass('defaultText') && field.val() != '')) {
// Sync the refine lists
// syncCheckboxLists($('#refineList input'), $('#advancedRefineList input'));
form.find('button').addClass('active');
$('#advancedSearchForm').submit();
} else {
$('#queryField').focus();
}
},
When I try to use the autocomplete drop-down by hitting enter, it seems to hit a "race condition" where the form will submit what I've typed rather than what autocomplete places into the textfield. Is there some way I can control the order of events so that the form.submit() will use what autocomplete fills into the text field?
The actual autocomplete dropdown menu is most likely represented as a styled list (or some other element) that is floated to be positioned below the textbox. On submit, have your function wait (a second or two max) for the autocomplete menu to be either destroyed or hidden. This will ensure that the plugin has time to fill in the textbox before the data is submitted.
EDIT
Try something like this:
$("#myDropdown").bind("autocompleteclose", function(){
// Continue with submitting your form
});
Use that where you would submit your form, and put the submitting code inside the callback. That way, it will wait for the autocomplete to close before submitting the form. You will want to add some kind of timeout to this to prevent it from submitting after a long delay (not sure when something like this might happen, though).