Jquery function not working with multiple function after DOM load - javascript

i have these two jquery functions and one of them is not getting called.but when i comment one of them the other one gets called and vice-versa.
1st
$(function() {
$("[id*=tvAi1] input[type=checkbox]").bind("click",
function() {
var table = $(this).closest("table");
if (table.next().length > 0 && table.next()[0].tagName == "DIV") {
//Is Parent CheckBox
var childDiv = table.next();
var isChecked = $(this).is(":checked");
if (isChecked) {
if ($('#CellNumberTextBox').val() == null || $('#CellNumberTextBox').val() === '') {
bootbox.alert(
"Please enter the Cell Number because you have asked for the MobileBankingService.");
this.checked = false;
$('#CellNumberTextBox').focus();
return false;
}
}
$("input[type=radio]", childDiv).each(function() {
if (isChecked) {
$(this).attr("checked", "checked");
return false;
} else {
$(this).removeAttr("checked");
}
});
}
});
$("#SaveButton").bind("click",
function (e) {
$("#hdMobile").val("");
var tv = document.getElementById("<%= tvAi1.ClientID %>");
var chkArray = tv.getElementsByTagName("input");
for (i = 0; i <= chkArray.length - 1; i++) {
if (i == 0) {
$.ajax({
type: "POST",
url: "AddNewCustomer.aspx/SetSession",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() {
}
});
}
if (chkArray[i].type == 'radio') {
if (chkArray[i].checked == true) {
if ($('#CellNumberTextBox').val() == null || $('#CellNumberTextBox').val() === '') {
bootbox.alert(
"Please enter the Cell Number because you have asked for the MobileBankingService.");
$('#CellNumberTextBox').focus();
$.hideprogress();
return false;
}
if ($("#hdMobile").val() == "" || $("#hdMobile").val() == null) {
$("#hdMobile").val(chkArray[i].value);
} else {
$("#hdMobile").val($("#hdMobile").val() + "," + chkArray[i].value);
}
}
}
}
});
});
2nd one
$(function() {
$("[id*=tvAi] input[type=checkbox]").bind("click",
function() {
var table = $(this).closest("table");
if (table.next().length > 0 && table.next()[0].tagName == "DIV") {
//Is Parent CheckBox
var childDiv = table.next();
var isChecked = $(this).is(":checked");
if (isChecked) {
if ($('#CellNumberTextBox').val() == null || $('#CellNumberTextBox').val() === '') {
bootbox.alert(
"Please enter the Cell Number because you have asked for the SMSService.");
this.checked = false;
$('#CellNumberTextBox').focus();
return false;
}
}
$("input[type=radio]", childDiv).each(function() {
if (isChecked) {
$(this).attr("checked", "checked");
return false;
} else {
$(this).removeAttr("checked");
}
});
}
});
$("[id*=tvAi] input[type=radio]").bind("click",
function() {
//hdSms
var parentDIV = $(this).closest("DIV");
if ($(this).is(":checked")) {
if ($('#CellNumberTextBox').val() == null || $('#CellNumberTextBox').val() === '') {
bootbox.alert("Please enter the Cell Number because you have asked for the SMSService.");
this.checked = false;
$('#CellNumberTextBox').focus();
return false;
}
$("input[type=checkbox]", parentDIV.prev()).attr("checked", "checked");
} else {
$("input[type=checkbox]", parentDIV.prev()).removeAttr("checked");
}
});
$("#SaveButton").bind("click",
function(e) {
$("#hdSms").val("");
var tv = document.getElementById("<%= tvAi.ClientID %>");
var chkArray = tv.getElementsByTagName("input");
for (i = 0; i <= chkArray.length - 1; i++) {
if (i == 0) {
$.ajax({
type: "POST",
url: "AddNewCustomer.aspx/SetSession",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() {
}
});
}
if (chkArray[i].type == 'radio') {
if (chkArray[i].checked == true) {
if ($('#CellNumberTextBox').val() == null || $('#CellNumberTextBox').val() === '') {
bootbox.alert(
"Please enter the Cell Number because you have asked for the SMSService.");
$('#CellNumberTextBox').focus();
$.hideprogress();
return false;
}
if ($("#hdSms").val() == "" || $("#hdSms").val() == null) {
$("#hdSms").val(chkArray[i].value);
} else {
$("#hdSms").val($("#hdSms").val() + "," + chkArray[i].value);
}
}
}
}
});
});
I tried combining them both but didnt helped.I want both of them to be called according to div enabled/disabled from my code-behind.Newbie here.Help Appreciated.

You may call your anonymous functions to set the jQuery's methods. Try something like this for the 2 functions:
$(function() {
/*Do stuff... */
})();
In your code, you set two anonymous functions (or closures). This functions will be never call (at least in your example). They only can be call (in your example) if you put the braces at the end (with some optional function's parameters).
Advantages:
Closures are useful because they let you associate some data (the lexical environment) with a function that operates on that data. This has obvious parallels to object oriented programming, where objects allow us to associate some data (the object's properties) with one or more methods.
Consequently, you can use a closure anywhere that you might normally
use an object with only a single method.
Please check the documentation.

Related

rerturning response of an ajax post

i am trying to check if an email exists in the db but the function doesn't return a value.
This is the code:
function checkemail(email)
{
var returnVal = "";
if (email.indexOf("#") != -1 && email.indexOf(".") != -1)
{
$.post( "registreren.php?email=" + email, function( response ) {
if(response == 1) { returnVal = 1; }
if(response == 2) { returnVal = 2; }
});
}
else
{
returnVal = 3;
}//email
return returnVal;
}
EDIT: email is send as a string
I short, You can not return values from ajax calls as it is asynchronous by nature, the statement return value executes before
To address such cases, use callback, a function accepted as argument and which is executed when response is been received (when asynchronous action is completed).
Try this:
function checkemail(email, callback) {
var returnVal = "";
if (email.indexOf("#") != -1 && email.indexOf(".") != -1) {
$.post("registreren.php?email=" + email, function(response) {
callback(response);
});
} else {
callback(3);
}
}
checkemail('abc#xyz.com', function(val) {
alert(val);
});
checkemail('INVALID_EMAIL', function(val) {
alert(val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Can you use something simple like below
$.ajax({
url: 'registreren.php',
type: 'post',
dataType: "json",
data: {'email': email},
success: function (response) {
if (response == 1)
{
returnVal = 1;
}
else
{
returnVal = 3;
}
}
});
instead of
$.post( "registreren.php?email=" + email, function( response ) {
if(response == 1) { returnVal = 1; }
if(response == 2) { returnVal = 2; }
});

How to properly put this code in noconflict mode

I am using prototype js and jquery in noconflict mode. It worked for all my code except for one.
I have done
<script type="text/javascript" src="js/jquery/jquery-2.1.3.min.js"></script>
<script>
$.noConflict();
///////////////////////////////////////////////////////////////////////////////
jQuery( document ).ready(function( $ ) {
// Code that uses jQuery's $ can follow here.
///////////////////////////////////////////////////////////////////////////////
//Here is the wall post code
var form = {
post : {
beforeSubmit: showRequest,
success: showResponse,
resetForm: true
}
};
$.fn.showLoader = function(){
$(this).removeClass('hide');
}
$.fn.hideLoader = function(){
$(this).addClass('hide');
}
//The code continues
$(document).ready(function(){
$('.floader').showLoader();
$('.facebook-share-box').ajaxForm(form.post);
$.get('profile_wall.php',function(data){
$('.wall').html(data);
$('.floader').hideLoader();
});
$("#geocomplete").geocomplete({
map: ".map_canvas",
details: "form",
types: ["geocode", "establishment"]
});
$('body').delegate('#shareType','click', function(e) {
e.preventDefault();
var positionArray = {};
positionArray['status'] = 0;
positionArray['photos'] = 80;
positionArray['videos'] = 160;
positionArray['location'] = 231;
$('.video').hideLoader('hide');
$('.image').hideLoader('hide');
$('.place').hideLoader('hide');
$('.shareType').val($(this).attr('class'));
$('.arrow').css("left", positionArray[$(this).attr('class')]);
if($(this).attr('class') == 'videos') {
$('.video').showLoader('hide');
$('.image').hideLoader('hide');
$('.place').hideLoader('hide');
}
if($(this).attr('class') == 'photos') {
$('.video').hideLoader('hide');
$('.image').showLoader('hide');
$('.place').hideLoader('hide');
}
if($(this).attr('class') == 'location') {
$('.video').hideLoader('hide');
$('.image').hideLoader('hide');
$('.place').showLoader('hide');
}
return false;
});
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
loadData();
}
});
});
function showRequest(formData, jqForm, options) {
type = $('.shareType').val();
for (var i=0; i < formData.length; i++) {
/*
if (!formData[i].value && formData[i].name == 'message') {
alert('Message could not be empty');
return false;
}
*/
if(type == 'photos') {
var fileName = document.getElementById("image").value
if (fileName == "") {
alert("Browse to upload a valid File with png/jpg/gif extension");
return false;
}
else if (fileName.split(".")[1].toUpperCase() == "PNG") {
}
else if (fileName.split(".")[1].toUpperCase() == "JPG") {
}
else if (fileName.split(".")[1].toUpperCase() == "JPEG") {
}
else if (fileName.split(".")[1].toUpperCase() == "GIF") {
}
else {
alert("File with " + fileName.split(".")[1] + " is invalid. Upload a validfile with png/jpg/gif extensions");
return false;
}
}
if(type == 'videos') {
if (!formData[i].value && formData[i].name == 'videoUrl') {
alert('Video Url could not be empty');
return false;
}
video = validateVideoUrl();
if(video == false){
alert('Not a valid youtube/vimeo video URL');
return false;
}
}
if(type == 'location') {
if (!formData[i].value && formData[i].name == 'location') {
alert('Place could not be empty');
return false;
}
if((!formData[i].value && formData[i].name == 'lat') || (!formData[i].value && formData[i].name == 'lng')){
alert('Not a valid place');
return false;
}
}
}
btn = $('#btn-share');
btn.button('loading');
}
//The response is shown here
function showResponse(responseText, statusText, xhr, $form) {
$('#wall-append').prepend(responseText);
btn.button('reset');
}
//This enable to validate url video
function validateVideoUrl(){
var url = $('#videoUrl').val();
var regYoutube = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
var regVimeo = /^.*(vimeo\.com\/)((channels\/[A-z]+\/)|(groups\/[A-z]+\/videos\/))?([0-9]+)/;
if(regYoutube.test(url) || regVimeo.test(url)) {
return true;
}else{
return false;
}
}
function loadData()
{
$('div.postloader').html('<img src="img/loader.gif">');
$.post("profile_get_data.php?lastID=" + $(".post-list:last").attr("id"),
function(data){
if (data != "") {
$(".post-list:last").after(data);
}
$('div.postloader').empty();
});
};
///////////////////////////////////////////////////////////////////////////////
});
</script>
But still it is not working. I don't know why it gives me an infinite load and then it gives me
Error: Permission denied to access property 'toString'
Please how to put jquery in noconflict mode with this ?

check on return value from jquery fails

I use jquery to validate the form, check the math-captcha and finally, send a mail.
The validation works fine and the mail works fine. There is only one problem. When my ajax returns false, the bool validCaptcha keeps always true...
$(document).ready(function() {
$("#confirm").on("click", function(e) {
e.preventDefault();
//Check name
var validName = true;
if ($("#name").val().length == 0) {
$("#name").addClass('error');
validName = false;
}
$("#name").change(function() {
$("#name").removeClass('error');
})
//Check email
var validEmail = true;
if ($("#email").val().length == 0 || validateEmail($("#email").val()) != true) {
$("#email").addClass('error');
validEmail = false;
}
$("#email").change(function() {
$("#email").removeClass('error');
})
//Check message
var validMessage = true;
if ($("#message").val().length == 0) {
$("#message").addClass('error');
validMessage = false;
}
$("#message").change(function() {
$("#message").removeClass('error');
})
//Check captcha
var validCaptcha = true;
$.ajax({
type: 'POST',
url: '../captcha/checkCaptcha.php',
data: $("#mailform").serialize(),
success: function(data) {
var result = $.trim(data);
if (result == 'false') {
$("#inputcaptcha").addClass('error');
validCaptcha = false;
} else if (result == 'true') {
$("#inputcaptcha").removeClass('error');
}
}
});
//Send email
if (validName == true && validEmail == true && validMessage == true && validCaptcha == true) {
$.ajax({
type: 'POST',
url: '../sendMail.php',
data: $("#mailform").serialize(),
success: function(data) {
var result = $.trim(data);
if (result == 'true') {
$("#succesmessage").removeClass('hidden');
}
else if (result == 'false') {
$("#failmessage").removeClass('hidden');
}
}
});
} else {
reloadCaptcha();
$("#inputcaptcha").val("");
}
});
});
In Firebug I see I get a 'false' back from checkCaptcha.php when e.g. I left the field blank of entered a wrong code.
checkCaptcha.php
session_start();
if ( !empty($_POST['inputcaptcha']) ) {
if ( $_POST['inputcaptcha'] == $_SESSION['security_number'] ) {
echo 'true';
}
else {
echo 'false';
}
}
else {
echo 'false';
}
To check I first checked the result-value from the captcha-ajax
alert(result)
//returned false as it should when leaving blank or entering wrong value
Then before calling the mail-ajax I called all bools
alert('validName='+validName+' & validEmail='+validEmail+' & validMessage='+validMessage+' & validCaptcha='+validCaptcha);
//validCaptcha was true, even when result was false...
What do I not see??
Simply put you can't do that since the validate captcha is an asynchronous request,
Instead you can move the email code to the validate captcha success handler like
$(document).ready(function () {
$("#confirm").on("click", function (e) {
e.preventDefault();
//Check name
var validName = true;
if ($("#name").val().length == 0) {
$("#name").addClass('error');
validName = false;
}
$("#name").change(function () {
$("#name").removeClass('error');
})
//Check email
var validEmail = true;
if ($("#email").val().length == 0 || validateEmail($("#email").val()) != true) {
$("#email").addClass('error');
validEmail = false;
}
$("#email").change(function () {
$("#email").removeClass('error');
})
//Check message
var validMessage = true;
if ($("#message").val().length == 0) {
$("#message").addClass('error');
validMessage = false;
}
$("#message").change(function () {
$("#message").removeClass('error');
})
//Check captcha
var validCaptcha = true;
if (validName == true && validEmail == true && validMessage == true) {
$.ajax({
type: 'POST',
url: '../captcha/checkCaptcha.php',
data: $("#mailform").serialize(),
success: function (data) {
var result = $.trim(data);
if (result == 'false') {
$("#inputcaptcha").addClass('error');
} else if (result == 'true') {
$("#inputcaptcha").removeClass('error');
$.ajax({
type: 'POST',
url: '../sendMail.php',
data: $("#mailform").serialize(),
success: function (data) {
var result = $.trim(data);
if (result == 'true') {
$("#succesmessage").removeClass('hidden');
reloadCaptcha();
$("#inputcaptcha").val("");
} else if (result == 'false') {
$("#failmessage").removeClass('hidden');
}
}
});
}
}
});
}
});
});

Javascript does user exists, returning value from ajax to late?

I have a script that tells a visitor if the username is already exist or not before he can proceed,
Below you see a part of my code;
EDIT: Ok I have read what you guys said, and modified it, but I still dont get it to work :S, my teacher doesn't know it either...
<script type="text/javascript">
jQuery(document).ready(function(){
// Smart Wizard
jQuery('#wizard').smartWizard({onFinish: onFinishCallback, onLeaveStep: onNextStep});
function onNextStep(){
validateSteps(function (next) { return next; });
}
function onFinishCallback(){
alert('Finish Clicked');
}
function UsernameExist(fullname, callback)
{
    var data = 'user='+ fullname;
    if(fullname) {
        $.ajax({
            type: "POST",
            url: "user_check.php",
            data: data,
async: false,
            beforeSend: function(html) {
                $("#msg_lastname").html('');
            },
            success: function(html){
                $("#msg_lastname").show();
                 $("#msg_lastname").append(html);
if(html.search("red") != -1)
{
callback(false);
}
else
{
callback(true);
}
            }
        });
}
}
function validateSteps(callback){
var isStepValid = true;
// validate step 1
var firstname = $('#firstname').val();
if(!firstname || (firstname.length < 3 || firstname.length > 10))
{
$('#msg_firstname').html('<br/><font color="red">Enter a first name, between 3 and 10 letters.</font>').show();
isStepValid = false;
}
else
{
$('#msg_firstname').html('').hide();
}
var lastname = $('#lastname').val();
if(!lastname || (lastname.length < 3 || lastname.length > 14))
{
$('#msg_lastname').html('<br/><font color="red">Enter a last name, between 3 and 14 letters.</font>').show();
isStepValid = false;
}
else
{
$('#msg_lastname').html('').hide();
}
var gender = $('#gender').val();
if(!gender || Number(gender) == -1)
{
$('#msg_gender').html('<br/><font color="red">Choose your gender!</font>').show();
isStepValid = false;
}
else
{
$('#msg_gender').html('').hide();
}
var age = $('#age').val();
if(!age || Number(age) > 90 || Number(age) < 21)
{
$('#msg_age').html('<br/><font color="red">Enter a age between 21 and 90.</font>').show();
isStepValid = false;
}
else
{
$('#msg_age').html('').hide();
}
var pin = $('#pin').val();
if(!pin || pin.length > 10 || pin.length < 4)
{
$('#msg_pin').html('<br/><font color="red">Enter a PIN between 4 and 10 numbers.</font>').show();
isStepValid = false;
}
else
{
$('#msg_pin').html('').hide();
}
if (isStepValid) {
UsernameExist(firstname + ' ' + lastname, function (exists) {
callback( exists );
});
} else {
callback( false );
}
}
jQuery('select, input:checkbox').uniform();
});
</script>
Now the problem is that when I run this script, it returns undefined, I guess because the UsernameExist is not done fast enough, and it seems the return UsernameExist is not waiting for it for some reason...
You are returning UsernameExists before it has been run.
Instead, call UsernameExists like this:
if (isStepValid) {
UsernameExist(firstname + ' ' + lastname, function (exists) {
return exists;
});
} else {
return false;
}
This works because UsernameExists expects a callback function and on success passes either true or false to callback().
you need just to set async option as false
function UsernameExist(fullname, callback) {
var data = 'user=' + fullname;
if (fullname) {
$.ajax({
type: "POST",
url: "user_check.php",
data: data,
async: false,
beforeSend: function (html) {
$("#msg_lastname").html('');
},
success: function (html) {
//your code after success
}
});
}
}
from jQuery documentation jQuery.ajax
If you need synchronous requests, set this option to false
so you need to execute your ajax call and wait until it's completely finish to execute what you want based on the result
Maybe you should call UsernameExist(fullname, callback) after jQuery load complete.
try this :
getScript('http://code.jquery.com/jquery-1.9.1.min.js', function () {UsernameExist(fullname, callback)});
function getScript(url, callback) {
var script;
script = document.createElement("script");
script.setAttribute('language', 'javascript');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', url);
var done = false;
vObj = script.onload;
script.onload = script.onreadystatechange = function () {
if (!done && (!this.readyState ||
this.readyState == "loaded" || this.readyState == "complete")) {
done = true;
if (typeof callback === 'function')
callback(this.ownerDocument.attributes);
}
};
var head = document.getElementsByTagName('head')[0];
head.appendChild(script);}
Try something like this :
// Smart Wizard
$('#wizard').smartWizard({onFinish: onFinishCallback, onLeaveStep: onNextStep});
function onNextStep() {
var isValid = validateSteps();
alert(isValid);
}
function onFinishCallback(){
alert('Finish Clicked');
}
function UsernameExist(fullname)
{
var data = 'user='+ fullname;
var userAlreadyExists = null;
if(fullname) {
$.ajax({
type: "POST",
url: "user_check.php",
data: data,
async: false,
beforeSend: function(html) {
$("#msg_lastname").html('');
},
success: function(html){
$("#msg_lastname").show();
$("#msg_lastname").append(html);
if(html.search("red") != -1)
{
userAlreadyExists = false;
}
else
{
userAlreadyExists = true;
}
}
});
}
return userAlreadyExists;
}
function validateSteps(){
...
if (isStepValid) {
return UsernameExist(firstname + ' ' + lastname);
} else {
return false;
}
}

Simplify syntax, how to avoid duplicate "if"?

I want to check a form when fields are error and disabling submit button as appropriate. I found a solution that works, but the syntax is ugly. :)
$(document).ready(function() {
$("#send").attr("disabled", "disabled");
$("#validatemail").keyup(function()
{
var email = $("#validatemail").val();
if (email != '')
{
if(isvalidmail(email))
{
// do stuff
}
else
{
// do stuff
}
}
else
{
// do stuff
}
});
$("#validatetitle").keyup(function()
{
var subject = $("#validatetitle").val();
if (subject != '')
{
if ((subject.length < 3) || (subject.length > 30))
{
// do stuff
}
else
{
// do stuff
}
}
else
{
// do stuff
}
});
$("#form_message").live('keyup', function()
{
// Duplicate is not smart!!!
var email = $("#validatemail").val(); // Duplicate
var subject = $("#validatetitle").val(); // Duplicate
if (
(isvalidmail(email)) // Duplicate
&&
(!((subject.length < 3) || (subject.length > 30))) // Duplicate
)
{
$("#send").removeAttr("disabled");
}
else
{
$("#send").attr("disabled", "disabled");
}
});
});
So how to simplify the code?
I spent several hours trying, but it did not work.
Thank you very much.
Regards,
Vincent
Try this.
$(document).ready(function() {
var isEmailValid = false;
var isSubjectValid = false;
$("#send").attr("disabled", "disabled");
$("#validatemail").keyup(function()
{
var email = $("#validatemail").val();
if (email != '')
{
if(isvalidmail(email))
{
// do stuff
isEmailValid = true;
}
else
{
// do stuff
isEmailValid = false;
}
}
else
{
// do stuff
}
});
$("#validatetitle").keyup(function()
{
var subject = $("#validatetitle").val();
if (subject != '')
{
if ((subject.length < 3) || (subject.length > 30))
{
// do stuff
isSubjectValid = true;
}
else
{
// do stuff
isSubjectValid = false;
}
}
else
{
// do stuff
}
});
$("#form_message").live('keyup', function()
{
// now just get all the set values here
$("#send").attr("disabled",(isEmailValid && isSubjectValid) ? "" : "disabled");
});
});
best way is to declare and initialize those variable globally and then use it ...and things which are being repeated in if condition place them in function and call it where you have to check those condition...
Try this:
$(document)
.ready(function () {
$("#send")
.attr("disabled", "disabled"), $("#validatemail")
.keyup(function () {
var a = $("#validatemail")
.val();
a != "" && isvalidmail(a)
}), $("#validatetitle")
.keyup(function () {
var a = $("#validatetitle")
.val();
a != "" && (3 > a.length || a.length > 30)
}), $("#form_message")
.live("keyup", function () {
var a = $("#validatemail")
.val(),
b = $("#validatetitle")
.val();
!isvalidmail(a) || 3 > b.length || b.length > 30 ? $("#send")
.attr("disabled", "disabled") : $("#send")
.removeAttr("disabled")
})
})

Categories