how to start click or change function from inside js - javascript

The problem is, $('#menu').val(menu).trigger('change'); and $('.parentcheck').val(0).attr('checked', true).trigger('click'); changes their state but doesn't fire their functions $("#menu").change(function () { and $(".parentcheck").click(function () {. How to deal with that problem?
My js code looks like that
$(document).ready(function () {
$("#parent").hide();
$(".parentcheck").click(function () {
if ($(this).val() === "0") {
$("#parent").hide().find('option:selected').removeAttr('selected');
}
if ($(this).val() === "1") {
if ($("#parent option").length > 0) {
$("#parent").show();
}
}
$("#menu").change();
});
$("#menu").change(function () {
var selectedmenu = $("#menu").val();
var parentcheck = $(".parentcheck:checked").val();
if (selectedmenu != '' && selectedmenu != '0') {
$.ajax({
type: "POST",
url: "processor/optionsgenerator.php",
data: {
menu: selectedmenu
},
success: function (result, status, xResponse) {
if (result != '') {
if (parentcheck == '0' || !$(".parentcheck").is(":checked")) {
$("#parent").hide();
} else {
$("#parent").html(result);
$("#parent").show();
}
} else {
alert('Baza ilə əlaqədə problem var.');
$("#parent").hide();
}
},
error: function (e) {
alert(e);
}
});
} else $("#parent").hide();
});
$('#menu').val(menu).trigger('change');
if(parent==0) {
$('.parentcheck').val(0).attr('checked',true).trigger('click');
}
else {
$('.parentcheck').val(1).attr('checked',true).trigger('click');
$('#parent').val(parent);
}
});

You are triggering the change before you've defined the change handler. Move your triggers to the end of your code block and it'll work fine.

Related

How can I include a function (and its parameter) within an event handler, without the function being called on page load?

I am refactoring this code
$("#one").on("click", function() {
if(operator === undefined) {
firstArray.push("1");
}
else {
secondArray.push("1");
}
});
$("#two").on("click", function() {
if(operator === undefined) {
firstArray.push("2");
}
else {
secondArray.push("2");
}
});
$("#three").on("click", function() {
if(operator === undefined) {
firstArray.push("3");
}
else {
secondArray.push("3");
}
});
$("#four").on("click", function() {
console.log("4");
if(operator === undefined) {
firstArray.push("4");
}
else {
secondArray.push("4");
}
});
$("#five").on("click", function() {
console.log("5");
if(operator === undefined) {
firstArray.push("5");
}
else {
secondArray.push("5");
}
});
$("#six").on("click", function() {
console.log("6");
if(operator === undefined) {
firstArray.push("6");
}
else {
secondArray.push("6");
}
});
$("#seven").on("click", function() {
console.log("7");
if(operator === undefined) {
firstArray.push("7");
}
else {
secondArray.push("7");
}
});
$("#eight").on("click", function() {
console.log("8");
if(operator === undefined) {
firstArray.push("8");
}
else {
secondArray.push("8");
}
});
$("#nine").on("click", function() {
console.log("9");
if(operator === undefined) {
firstArray.push("9");
}
else {
secondArray.push("9");
}
});
$("#zero").on("click", function() {
console.log("0");
if(operator === undefined) {
firstArray.push("0");
}
else {
secondArray.push("0");
}
});
into this
function pushNumber(numberToPush) {
if(operator === undefined) {
firstArray.push(numberToPush);
}
else {
secondArray.push(numberToPush);
}
}
$("#one").on("click", pushNumber("1"));
$("#two").on("click", pushNumber("2"));
$("#three").on("click", pushNumber("3"));
$("#four").on("click", pushNumber("4"));
$("#five").on("click", pushNumber("5"));
$("#six").on("click", pushNumber("6"));
$("#seven").on("click", pushNumber("7"));
$("#eight").on("click", pushNumber("8"));
$("#nine").on("click", pushNumber("9"));
$("#zero").on("click", pushNumber("0"));
When I try the above code, the pushNumber function is being called on page load. I understand that this is happening because I have put parentheses, thereby calling the function. But I do not know how I can pass a parameter to the function without doing it this way.
I'd appreciate some help, thanks.
What you want to do is "curry" a function, or generate a new function that already has some arguments added into it.
First, we'll make a function to generate a new function for each click handler:
function generateHandler(argument) {
return function() {
pushNumber(argument);
};
}
Then, you can use it like this:
$("#one").on("click", generateHandler("1"));
What you want is something called partial application or currying. You can do it manually for your case with a higher-order function, like this:
function pushNumber(numberToPush)
return function() {
if(operator === undefined) {
firstArray.push(numberToPush);
} else {
secondArray.push(numberToPush);
}
};
}
But many utiility libraries also offer a curry or partial function that you might be able to use to wrap your function.

Ajax continuous pull from database

I have literally just started programing with Ajax and cant get this to work.
Here is what I have so far:
var oldAction = '';
function updateCheck() {
$.ajax({
url: 'check_status.php',
success: function (data) {
if (data.length != oldAction) {
if (data.length == '4') {
playSong();
} else {
pauseSong();
}
}
oldAction = data.length;
}
});
}
setInterval('updateCheck();', 1000);
Does anyone know why this would not be working?
Thanks
Sure. length() is looking for an integer, but you are comparing it to a string.
If oldAction really needs to be a string, then you need to do something like this:
if (data.length != Number(oldAction)) {
if (data.length == 4) {
playSong();
} else {
pauseSong();
}
};
try this:
function updateCheck() {
var
oldAction = 0,
callAjax = function () {
$.ajax({
url: 'check_status.php',
success: function (data) {
if (data.length != oldAction) {
(data.length == 4) ? playSong() : pauseSong();
}
oldAction = data.length;
}
});
};
setInterval(callAjax, 1000);
}
updateCheck();
​

JQuery - where to add .on()/.live() to function?

var refreshId = setInterval(function() {
$('#livelist').load('/scripts/livelist.php', { guestlist:'<?php echo $_GET['guestlist']; ?>'});
}, 5000);
$.ajaxSetup({ cache: false });
I know I need to attach the .live() event handler to prevent the function from triggering other events (what's currently happening), but where do I add it?
Full Script:
$(document).ready(function() {
$("input#name").select().focus();
$('#livelist').load('/scripts/livelist.php', { guestlist:'<?php echo $_GET['guestlist']; ?>'});
var refreshId = setInterval(function() {
$('#livelist').load('/scripts/livelist.php', { guestlist:'<?php echo $_GET['guestlist']; ?>'});
}, 5000);
$.ajaxSetup({ cache: false });
$("input#name").swearFilter({words:'bob, dan', mask:"!", sensor:"normal"});
var tagCheckRE = new RegExp("(\\w+)(\\s+)(\\w+)");
jQuery.validator.addMethod("tagcheck", function(value, element) {
return tagCheckRE.test(value);
}, "");
$("#addname").validate({
invalidHandler: function(form, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
$('#naughty').fadeIn('fast');
$('#naughty').delay('1000').fadeOut('fast');
} else {
$('#naughty').hide();
}
}
});
$('#showall').live('click', function() {
$('#showall').hide();
$('div#shownames').slideDown('fast');
});
jQuery(document).ajaxStart(function(){
$("input#name").blur();
$('#working').show();
$('#event-box').fadeTo('fast', 0.5);
})
var names = '';
var dot = '.';
$('#addname').ajaxForm(function() {
var options = {
success: function(html) {
/* $("#showdata").replaceWith($('#showdata', $(html))) */
var value = $("input#name").val().toUpperCase();;
$("span.success").text(value);
if (names == '') {
names = value;
}
else {
names = ' ' + value + ', ' + names;
$("span#dot").text(dot);
}
$("span#name1").text(names);
$('#working').fadeOut('fast');
$('#success').fadeIn('fast');
$('#added-names').fadeIn('fast');
$('#success').delay('600').fadeOut('fast');
$("input#name").delay('1200').select().focus();
$('#event-box').delay('600').fadeTo('fast', 1.0);
$(':input','#addname')
.not(':button, :submit, :reset, :hidden')
.val('')
},
cache: true,
error: function(x, t, m) {
if(t==="timeout") {
$('#working').fadeOut('fast');
$('#fail').fadeIn('fast');
$('#fail').delay('600').fadeOut('fast');
} else {
$('#working').fadeOut('fast');
$('#fail').fadeIn('fast');
$('#fail').delay('600').fadeOut('fast');
alert(t);
}
}
}
$(this).ajaxSubmit(options);
$('body').select().focus();
});
$("input").bind("keydown", function(event) {
var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
if (keycode == 13) {
document.getElementById('#submit').click();
return false;
} else {
return true;
}
});
});
The ajaxForm function is being triggered using my current implementation.
The fault:
jQuery(document).ajaxStart(function(){
$("input#name").blur();
$('#working').show();
$('#event-box').fadeTo('fast', 0.5);
})
As .ajaxStart() is a global parameter, it was being triggered during every AJAX call, including .load(), I'm surprised no one spotted it.

Weird Error Occurred During Function Run

I have the following function :
var appendStructure = {
init : function(wrapper,structure,cls,callback) {
$(wrapper).appendTo(container).hide()
var object = $(container).find(cls);
$(structure.join('')).appendTo(object);
showObj(object,function() {
if(opts.centerObj == true) {
$(window).resize(function() {
var cssProps = getProps(object);
object.css(cssProps);
});
}
if(typeof callback == 'function') {
callback();
}
});
}
}
And the other functions that are called within it:
var getProps = function(obj) {
return {
'position' :'absolute',
'top' : (($(window).height() - $(obj).outerHeight()) / 2)+'px',
'left' : (($(window).width() - $(obj).outerWidth()) / 2)+'px'
}
}
var showObj = function(obj,callback) {
return setTimeout(function () {
if(opts.centerObj == true) {
var cssProps = getProps(obj);
obj.css(cssProps).fadeIn('slow');
}
else {
obj.fadeIn('slow');
}
if(typeof callback == 'function') {
callback();
}
}, 1500);
}
And I run the function like this:
if(appendStructure.init(wrapper.login,structure.login,'.content-login')){
console.log('Object Appended');
}
else {
console.log('Error');
}
My question is, why is the console outputting Error, because the function actually works and everything that is suppose to happen, happens ?
appendStructure.init does not return any value, hence the return value will be undefined. undefined evaluates to false, so the else branch of your if...else statement is executed.

How do I block a dialog("open") call with jQuery/UI's Dialog

I'm trying to create a function that shows a modal dialog which when called blocks until the dialog is closed, this will allow for a result to be returned to the caller
The following function is an attempt which has two problems.
It returns the result while the dialog is still open.
The selector test does not find the dialog, inspecting with firebug reveals that the id element is lost once the dialog is created.
.
function getCountrySelection() {
var ctryCode;
var dlg = $("#JS-field-dlg-ctry-select");
if (dlg.size() === 0) {
dlg = $("<div id='JS-field-dlg-ctry-select' title='Select Country' class='dialog-fields'></div>");
dlg.append("Customer found in both Australia and New Zealand");
dlg.dialog({
autoOpen: false,
width: 400,
height: 160,
modal: true,
buttons: {
"Australia": function() {
ctryCode = "au";
$(this).dialog("close");
},
"New Zealand": function() {
ctryCode = "nz";
$(this).dialog("close");
},
"Cancel": function() {
$(this).dialog("close");
}
}
});
}
dlg.dialog('open');
return ctryCode;
}
EDIT: I thought I'd show how I'm calling this:
buttons: {
"Find": function() {
var custAu = JS.sales.getCustomer("au", inpCust.val());
var custNz = JS.sales.getCustomer("nz", inpCust.val());
var cust;
if (custAu === undefined && custNz === undefined) {
alert('No customer could be found with that number.');
return;
} else if (custAu !== undefined && custNz !== undefined) {
var ctry;
getCountrySelection(function(result) {
ct = result;
});
if (ctry === "au") {
cust = custAu;
} else if (ctry === "nz") {
cust = custNz;
} else {
return;
}
} else if (custNz === undefined) {
cust = custAu;
} else {
cust = custNz;
}
if (cust) {
$(this).dialog("close");
// Do something with cust.
} else {
alert('Customer could not be found.');
}
},
"Cancel": function() {
$(this).dialog("close");
}
}
There is no way to block execution until the dialog closes; JavaScript does not allow to "suspend" execution. Your best bet is to change the contract of your function; instead of returning the value straight away, it should accept a callback function that it will call with the result as soon as the dialog is dismissed. Then the code calling this will provide a suitable callback in which it can continue its execution.
Something like this:
function getCountrySelection(callback) {
(...)
buttons: {
"Australia": function() {
$(this).dialog("close");
callback("au");
},
"New Zealand": function() {
$(this).dialog("close");
callback("nz");
},
"Cancel": function() {
$(this).dialog("close");
callback();
}
}
});
}
dlg.dialog('open');
}
Then use:
getCountrySelection(function(result) {
if (result) {
...handle result...
} else {
...the user cancelled the dialog...
}
});
This is basically the same thing as with AJAX calls; you can't "suspend" your AJAX call to wait until the AJAX actually completes and returns the result, hence "asynchronous".
EDIT: In your specific example, you could use it like this:
buttons: {
"Find": function() {
var custAu = JS.sales.getCustomer("au", inpCust.val());
var custNz = JS.sales.getCustomer("nz", inpCust.val());
if (custAu === undefined && custNz === undefined) {
alert('No customer could be found with that number.');
return;
} else if (custAu !== undefined && custNz !== undefined) {
getCountrySelection(function(ctry) {
var cust;
if (ctry === "au") {
cust = custAu;
} else if (ctry === "nz") {
cust = custNz;
}
handleCustomer(cust);
});
} else if (custNz === undefined) {
handleCustomer(custAu);
} else {
handleCustomer(custNz);
}
function handleCustomer(cust) {
if (cust) {
$(this).dialog("close");
// Do something with cust.
} else {
alert('Customer could not be found.');
}
}
},
"Cancel": function() {
$(this).dialog("close");
}
}

Categories