Conditionally load jquery throbber plugin - asp.net

I have the code below that shows a throbber and makes a getJSON call to an MVC action when the user changes an entry in a select. This all works great except there is a default -- select -- element in the list for which I don't want the getJSON to run.
However, I can't work out how to apply conditional logic to hooking this event. The conditional logic is shown as the if(selectedValue == -1) But the throbber still runs as I've hooked it in the first line. I've tried removing the first line that hooks the change event and use $.throbberShow(..) inline just prior to the getJSON call but for some reason this doesn't show the throbber.
Any help greatly appreciated.
$("#selectlist").throbber("change", { ajax: false, image: "images/ajax-loader-line.gif" });
$("#selectlist").change(
function () {
var selectedValue = $("#selectlist").val();
if (selectedValue != -1) {
//Tried doing $.throbberShow(...) here without success
$.getJSON("/Candidate/GetAddress", { id: selectedValue }, function (data, textStatus) {
if (textStatus == "success") {
$("#selectlist").val(data.Line1)
$("#selectlist").val(data.Line2)
$("#selectlist").val(data.Line3)
$("#selectlist").val(data.Town)
}
$.throbberHide();
});
}
}
);

It is more a hack than a solution as throbber doesn't support conditions but this should work:
$("#selectlist").throbber("change", { ajax: false, image: "images/ajax-loader-line.gif", delay: "500" });
$("#selectlist").change(
function () {
var selectedValue = $("#selectlist").val();
if (selectedValue != -1) {
$.getJSON("/Candidate/GetAddress", { id: selectedValue }, function (data, textStatus) {
if (textStatus == "success") {
$("#selectlist").val(data.Line1)
$("#selectlist").val(data.Line2)
$("#selectlist").val(data.Line3)
$("#selectlist").val(data.Town)
}
$.throbberHide();
});
} else {
$.throbberHide();
}
}
);

Related

Why isn't my AJAX call to an HTTPHandler working?

I am attempting to re-create the solution seen here for keeping a session alive by using an HTTPHandler and making an AJAX call to it.
The solution does not appear to have worked, and when I tried to debug it by adding an alert(); just before the $.get(); the alert(); never got fired off. I copied and pasted the code from the example, so I'm not missing a semicolon or something. I even set an alert(); before the setTimeout(); and that one worked!
function setHeartbeat() {
alert("I get here!");
setTimeout("heartbeat()", 300000); // every 5 min
}
function heartbeat() {
alert("I never seem to fire off!");
$.get(
"/SessionHeartbeat.ashx",
null,
function(data) {
setHeartbeat();
},
"json"
);
}
Any thoughts?
Both slon and Hans Kesting were right one the money.
The working javascript is:
$(document).ready(function () {
//alert("Document is ready.");
// set the initial call
setHeartbeat();
function setHeartbeat() {
//alert("setHeartbeat");
setInterval(function () {
heartbeat();
}, 10000); // every 10 sec
}
function heartbeat() {
//alert("heartbeat");
$.get(
"/SessionHeartbeat.ashx",
null,
function(data) {
setHeartbeat();
},
"json"
);
}
});
Thank you both!

Select2 not working in Jquery-Steps wizard plugin

Please help with the script function on how to make select2 plugin work in wizard jquery template it is not firing and i'm using the search box, when it clicked it jams.Thank you
$('.class').select2(); AFTER $('#form').steps();
This has helped me thanks but..
$("#form").steps({
bodyTag: "fieldset",
onStepChanging: function (event, currentIndex, newIndex)
{
// Always allow going backward even if the current step contains invalid fields!
if (currentIndex > newIndex)
{
return true;
}
// Forbid suppressing "Warning" step if the user is to young
if (newIndex === 3 && Number($("#age").val()) < 18)
{
return false;
}
var form = $(this);
// Clean up if user went backward before
if (currentIndex < newIndex)
{
// To remove error styles
$(".body:eq(" + newIndex + ") label.error", form).remove();
$(".body:eq(" + newIndex + ") .error", form).removeClass("error");
}
// Disable validation on fields that are disabled or hidden.
form.validate().settings.ignore = ":disabled,:hidden";
// Start validation; Prevent going forward if false
return form.valid();
},
onStepChanged: function (event, currentIndex, priorIndex)
{
// Suppress (skip) "Warning" step if the user is old enough.
if (currentIndex === 2 && Number($("#age").val()) >= 18)
{
$(this).steps("next");
}
// Suppress (skip) "Warning" step if the user is old enough and wants to the previous step.
if (currentIndex === 2 && priorIndex === 3)
{
$(this).steps("previous");
}
},
onFinishing: function (event, currentIndex)
{
var form = $(this);
// Disable validation on fields that are disabled.
// At this point it's recommended to do an overall check (mean ignoring only disabled fields)
form.validate().settings.ignore = ":disabled";
// Start validation; Prevent form submission if false
return form.valid();
},
onFinished: function (event, currentIndex)
{
var form = $(this);
// Submit form input
form.submit();
}
}).validate({
errorPlacement: function (error, element)
{
element.before(error);
},
rules: {
confirm: {
equalTo: "#password"
}
}
});
//IMPORTANT
var form =$("#form");
form.find("#personel_id").select2({
theme: 'bootstrap4',
});

Submitting form using Casperjs Error

I'm trying to scrape products with color and size variations.
Every variation is a form and to get the next variation I'm clicking on radio button and it is doing a form submit action on each click.
I have tried to click it using
1. “casper.getElementsInfo(element)[0].click();”
2. “document.querySelectorAll(element)[2].click();”
3. “casper.thenClick('element');”
4. “casper.evaluate(function(){document.querySelectorAll(element)[2].click();});”
After every click I'm doing a casper wait for 8 seconds !
So here is my problem Casperjs is getting error after clicking the next color/size
var casper = require('casper').create({
viewportSize: {
width: 1920,
height: 1080
},
pageSettings: {
loadImages: false,
loadPlugins: false
}
});
casper.then(function () {
self.thenOpen("https://scubapro.johnsonoutdoors.com/fins/fins/seawing-nova-fin-full-foot", function () {
casper.then(function () {
var varitoinCount = document.querySelectorAll('div#edit-attributes-field-swatch-taxonomy > div input').length;
var i = 0;
casper.repeat(varitoinCount + 1, function () {
try {
document.querySelectorAll('div#edit-attributes-field-swatch-taxonomy > div input')[i].click();
casper.log('we got to anhoter variatoin ...' + i);
} catch (error) {
console.log(error);
}
i++;
});
});
});
});
try {
casper.run();
} catch (e) {
consol.log("Error..... " + e);
}
(TypeError: undefined is not a constructor )
And btw when I'm doing the same thing in a console it works fine
You have to understand that accessing DOM is not possible in Casper environment. You should switch to browser environment to execute your DOM selectors by using Casper's evaluate method. Basically it used to get some information from within browser or to manually do some actions with javascript. To understand it you have a whole section dedicated for that in official documentation.
That being said, I amended your code to properly click on different color variation inputs.
var casper = require('casper').create({
viewportSize: {
width: 1920,
height: 1080
},
pageSettings: {
loadImages: false,
loadPlugins: false
}
});
casper
.start()
.thenOpen("https://scubapro.johnsonoutdoors.com/fins/fins/seawing-nova-fin-full-foot", function () {
var varitoinCount = this.evaluate(function() {
return document.querySelectorAll('div#edit-attributes-field-swatch-taxonomy > div input').length;
});
var i = 0;
this.repeat(varitoinCount + 1, function() {
this.evaluate(function(iterator) {
document.querySelectorAll('div#edit-attributes-field-swatch-taxonomy > div input')[i].click();
}, i);
i++;
})
});
try {
casper.run();
} catch (e) {
console.log("Error..... " + e);
}
However it still doesn't change the color since website(for some reason) needs to take 2 clicks to change the color and I suggest that you throw in some waitFor functions to be sure that color has changed.

Knockout asyncCommand - hit from a method

I want to alter how an asyncCommand is being hit (currently from a button), so I would need to access the asyncCommand from code. I don't want to have to alter what this asyncCommand is doing, it is dealing with payment details.
I have tried Googling but I cant find anything, I am also new to KO.
This is what I'm trying to achieve:
Click on a button (a separate button with its own asyncCommand method
which checks a flag) The 'execute' will do the following:
If (flag) - show modal
modal has two options - Continue / Cancel
If continue - hit asyncCommand command for original button (card payment one).
If cancel - go back to form
If (!flag)
Hit asyncCommand command for original button (card payment one).
Can this be done?
Thanks in advance for any help.
Clare
This is what I have tried:
FIRST BUTTON
model.checkAddress = ko.asyncCommand({
execute: function (complete)
{
makePayment.execute();
if (data.shippingOutOfArea === true || (data.shippingOutOfArea === null && data.billingOutOfArea === true)) {
model.OutOfArea.show(true);
}
complete();
},
canExecute: function (isExecuting) {
return !isExecuting;
}
});
ORIGINAL BUTTON
model.makePayment = ko.asyncCommand({
execute: function (complete) {
}})
MODAL
model.OutOfArea = {
header: ko.observable("Out of area"),
template: "modalOutOfArea",
closeLabel: "Close",
primaryLabel: "Continue",
cancelLabel: "Change Address",
show: ko.observable(false), /* Set to true to show initially */
sending: ko.observable(false),
onClose: function ()
{
model.EditEmailModel.show(false);
},
onAction: function () {
makePayment.execute();
},
onCancel: function ()
{
model.EditEmailModel.show(false);
}
};
You will have two async commands actually for this scenario. One to open up the modal and another one for the modal.
Eg:
showPaymentPromptCmd = ko.asyncCommand({
execute: function(complete) {
if (modalRequired) {
showModal();
} else {
makePayement();
}
complete();
},
canExecute: function(isExecuting) {
return !isExecuting;
}
});
//Called by Continue button on your modal.
makePaymentCmd = ko.asyncCommand({
execute: function(complete) {
makePayement();
complete();
},
canExecute: function(isExecuting) {
return !isExecuting;
}
});
var
function makePayement() {
//some logic
}

How to trigger a validation on only Button Click or Input:Submit

I am using Update Panel in my asp page and I am doing JQuery Validation on Asynchronous Postback...
I just want to validate my form on only button clicks or submits...
My problem is..all my buttons are in different formviews and won't load at a time...that's why I am unable to take the button id's and use the click events..here is my code..
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(ValidateMyForm);
function ValidateMyForm(sender, args) {
var objPost = args.get_postBackElement();
if (objPost === null || objPost === undefined) return;
if (objPost.id == '<%= ((Button)(formViewinfo.FindControl("btnUpdate"))).ClientID %>') {
$('#pnlerrors').fadeOut('fast');
$('#pnlItemErrors').fadeOut('fast');
var isValid = $('#form1').validate({
errorClass: 'error',
invalidHandler: function (e, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
$('#pnlerrors').html('<p> Please correct the errors </p>').fadeIn('fast');
document.location.href = '#pnlerrors';
}
}, submitHandler: function () {
}
}).form();
if (!isValid) {
CancelPostback(sender, args);
} else {
}
}
//this is for rest of buttons
else {
$('#pnlItemErrors').fadeOut('fast');
$('#pnlerrors').fadeOut('fast');
var isValid = $('#form1').validate({
errorClass: 'error',
invalidHandler: function (e, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
$('#pnlerrors').fadeOut('fast');
document.location.replace('#', '#pnlItemErrors');
$('#pnlItemErrors').html('<p> Please correct the errors </p>').fadeIn('fast');
document.location.href = '#pnlItemErrors';
}
}, submitHandler: function () {
}
}).form();
if (!isValid) {
CancelPostback(sender, args);
} else {
}
}
}
All I want to do is: 2nd time validation on only button submit not for everything...I do get other postbacks on this page and those post backs also gets validated each time (I want to Avoid this)...
I don't know this approach is good or not...I am struggling with this from long time..I really appreciate you help...
On the assumption that you don't want to submit the form when someone presses the enter button, and that you only want to submit the form on pressing a submit button:
$(document).ready(
function(){
$('form').keypress(
function(event){
if (event.keyCode == '13'){
return false;
}
});
$('input:submit').click(
function(){
$(this).closest('form').submit();
});
$('form').submit(
function(){
$('#success').text('form submitted! (Not really...)');
return false;
// Just to stop the error messages
// in this demo.
});
});
There's a JS Fiddle demo, here: http://jsfiddle.net/davidThomas/5PaWz/.
If I'm mistaken in my assumptions, please leave a comment and I'll try to correct myself.
if your problem is just about finding the buttons the need to have validations then
one way of getting around this is to add a class to the buttons that you want to trigger validation, for example :
<asp:button id="btn1" cssclass="Validate"/>
then you can grab all these buttons in JQuery:
var buttons = $('.Validate');
get each button id:
$(buttons).each(function(){
var id = this.id;
});
ohh..god finally found the solution for my problem...First of all my apologizes if my question is not clear....
My validation works on asynchronous post backs...I just want validate my form on button clicks..i do have an asp.net grid view in my page..if i click on paging or something on the grid it fires validation...i want avoid this..
for this what i did is...i am capturing the postback element with the following statement.
var objPost = args.get_postBackElement();
then i am checking for type..
if (objpost.type == 'submit') { do validation }
else { don't }..
this ends my 2days struggle...
thank you very much your support and help...
Try different approach.
Use asp.Net Button with UseSubmitBehavior=true for submission
and use asp.Net Button with UserSubmitBehavior=false for buttons that you don't want them to fire the validation process that. add this following code to your form
function ValidateForm()
{
var errors ="";
if (typeof(Page_ClientValidate) == 'function')
{
if (typeof (Page_ClientValidate) == 'function') { Page_ClientValidate(); }
if (!Page_IsValid)
{
for (i = 0; i < Page_Validators.length; i++) {
var inputControl = document.getElementById(Page_Validators[i].controltovalidate);
if (!Page_Validators[i].isvalid) {
errors = errors + ";" + Page_Validators[i].errormessage;
inputControl.style.border ="solid 2px #FF0000";
}
}
}
return Page_IsValid;
}
return true;
}
$(document).ready(function(){
/*********************************************************************/
///handle form submittion and run validation prior to that
///if a textbox has required field validator, stop form submittion and
/// highlight the text box
/*********************************************************************/
$('#form1').submit(function(){
return ValidateForm();
});

Resources