jquery function onclick and onload myFunction is not a function - javascript

I currently have an .on(click) where an ajax call happens now the problem is I want everything in the .on(click) to happen also when the pages loads.
My plan is to create a function and put everything that happens in the .on(click) in this function. And when the pages loads I want this function to trigger too.
Here's what I've tried but doesn't seem to be working.
my .on(click):
$('.changetypevastgoed').on('click', function(e){
var termid = $(this).data('termid');
$('#slctypevastgoed').val(termid);
$('#vastgoedtypes').find('.active').removeClass('active');
$(this).addClass('active');
e.preventDefault();
$.ajax({
type: 'POST',
dataType: "json",
data: "termid=" + termid,
url: $('body').data('theme-url') + '/lib/getsearchoptions.php',
success: function(result) {
var juistekeyslanden=[];
$.each(result.landen, function(key1, value1) {
$.each(value1, function(key2, value2) {
if (key2 == termid){
juistekeyslanden.push(key1);
}
});
});
$('select#land').find('option').each(function() {
$(this).attr("disabled", true);
var currentoption = $(this).attr("data-id");
if ($.inArray(currentoption, juistekeyslanden) != -1){
$(this).attr("disabled", false);
}
}).after(function( x ) {
$('.chosen').trigger('chosen:updated');
});
var juistekeysoppervlakten=[];
$.each(result.oppervlakten, function(key1, value1) {
$.each(value1, function(key2, value2) {
if (key2 == termid){
juistekeysoppervlakten.push(key1);
}
});
});
$('select#oppervlakte').find('option').each(function() {
$(this).attr("disabled", true);
var currentoption = $(this).attr("data-id");
if ($.inArray(currentoption, juistekeysoppervlakten) != -1){
$(this).attr("disabled", false);
}
}).after(function( x ) {
$('.chosen').trigger('chosen:updated');
});
var juistekeyspostocodes=[];
$.each(result.postcodes, function(key1, value1) {
$.each(value1, function(key2, value2) {
if (key2 == termid){
juistekeyspostocodes.push(key1);
}
});
});
$('select#postcode').find('option').each(function() {
$(this).attr("disabled", true);
var currentoption = $(this).attr("data-id");
if ($.inArray(currentoption, juistekeyspostocodes) != -1){
$(this).attr("disabled", false);
}
}).after(function( x ) {
$('.chosen').trigger('chosen:updated');
});
}
});//success
});
So I've tried putting my AJAX call in a function like so:
$.fn.myfunction = function () {
$.ajax({
...
};
I set this right under my
jQuery(document).ready(function( $ ) {
And in my on.click I do this:
$('.changetypevastgoed').myFunction();
On this line I get this error
$(...).myFunction is not a function

$(document).ready(function(){
$(".changetypevastgoed").trigger("click");
});
have u tried something like this ?

Related

TypeError: g[b] is undefined

I am trying to pass down the coding value to datetimepicker in order to disable the specific day using "daysOfTheWeekDisabled". The problem is I get TypeError: g[b] is undefined as an error when I check the console. What could be the problem?
Here's the code:
<script type="text/javascript">
$(document).ready(function () {
$('#VehicleIDDD').change(function () {
var vehdrv = ($('#VehicleIDDD :selected').val());
var val = vehdrv.split("_");
var drvid = val[1];
var vehid = val[0];
if (drvid == "0") {
$("#DriverID > option").each(function () {
$(this).show();
});
}
else {
//console.log(vehid + "= with driver " + drvid);
$("#DriverID > option").each(function () {
var option_val = $(this).val();
if (option_val != drvid) {
$(this).hide();
}
});
}
$("#DriverID").val(drvid)
$("#VehicleID").val(vehid);
$.ajax({
type: 'GET',
url: '#Url.Action("checkCodingDay", "Reservation")',
data: { "VehicleID": vehid },
dataType: 'json',
success: function (data) {
var coding = data[0].CodingDay
daysOfWeekDisabled(coding);
},
error: function (emp) {
alert('error');
}
});
}).trigger("change");
})
function daysOfWeekDisabled(coding) {
$("#datetimepicker").datetimepicker({
daysOfWeekDisabled: coding,
});
$("#datetimepicker").datetimepicker('refresh');
}
</script>
If you need more details just comment down and I'll add what you're looking for.
UPDATE

Only focus in the first element

I did a search form that can navigate between the results using the arrows up and down key. But only works with the first results, if you want to navigate again you need to focus on the search input text again, I can't navigate pressing up or down again if i don't do this.
JSFiddle: http://jsfiddle.net/gaw7g332/6/
Js code:
/* JS File */
// Start Ready
$(document).ready(function() {
// Icon Click Focus
$('.buscar-icon').click(function(){
$('input#search').focus();
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#search').val();
$('b#search-string').text(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
$("input#search").on("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$("ul#results").fadeOut();
$('p#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('p#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
});
$("input#search").on("keydown", function(e) {
var $listItems = $('ul#results li');
var $listItemsa = $('ul#results li a');
var key = e.keyCode,
$selected = $listItems.filter('.selected'),
$current;
if ( key != 40 && key != 38 ) return;
$listItems.removeClass('selected');
if ( key == 40 ) // Down key
{
if ( ! $selected.length || $selected.is(':last-child') ) {
$current = $listItems.eq(0);
event.preventDefault();
}
else {
$current = $selected.next();
event.preventDefault();
}
}
else if ( key == 38 ) // Up key
{
if ( ! $selected.length || $selected.is(':first-child') ) {
$current = $listItems.last();
event.preventDefault();
}
else {
$current = $selected.prev();
event.preventDefault();
}
}
$.fn.focusWithoutScrolling = function(){
var x = $(document).scrollLeft(), y = $(document).scrollTop();
this.focus();
window.scrollTo(x, y);
return this; //chainability
};
var $currenta = $current.children();
$currenta.focusWithoutScrolling();
$current.addClass('selected');
event.preventDefault();
});
That is because your event listener is only checking the key event on the input field you can add the list of results to the listener like this:
$("input#search, #results").on("keydown", function(e) {
.....
});
This should allow to navigate the results
fiddle

submit ajax request on keyboard ENTER

I have on click jquery that submits ajax request.
There are no forms.
I'd like keyboard ENTER to be used also to submit ajax request.
I've allot of these buttons, this confuses me as I cannot simply do:
$('#myForm input:text').keypress(function (e) {
if (e.which == 13) {
$("#button1").click()
}
});
My currect on click event looks like this (how do I extend this to accomodate ENTER?)
//Check answer
$("body").on("click", ".unlocked figcaption .check", function(){
var logo_id = $(this).parent().attr("id");
var answer = $("#" + logo_id + " input[name=guesslogo]");
var logo_lang = answer.attr("data-lang");
answer.removeAttr("class").attr("disabled","true");
//Submit answer for review
$.ajax({
url: "actions.php",
get: "GET",
data: "answer=" + answer.val() + "&logo_id=" + logo_id + "&logo_lang=" + logo_lang,
cache: false,
success: function (data){
var response = jQuery.parseJSON(data);
if (response.result == 1) {
answer.addClass("correct").siblings(".clear, .hint").fadeTo("slow","0.4");
answer.parent().append('<div class="alert"><h3>Correct!</h3> <p>Score: '+ response.score +'</p></div>');
$("#" + logo_id).siblings(".logo").removeClass("logo").addClass("answered").removeAttr("style");
snd_correct.play();
//update user_score and user_level values in leaderboard and header widgets
var this_user = $("header aside").attr("data-usern");
if (this_user) {
var this_user_score = $("header aside .user_score").text();
var this_user_level = $("header aside .user_level").text();
$("[data-usern="+ this_user +"] .user_score").empty().append(parseInt(this_user_score) + parseInt(response.score));
if (response.level_up == 1) {
var new_level = parseInt(this_user_level) +1;
$("[data-usern="+ this_user +"] .user_level").empty().append(new_level);
update_view(new_level);
}
//
update_level_progress_bar();
}
} else if (response.result == 0) {
answer.addClass("wrong").removeAttr("disabled");
snd_wrong.play();
} else if (response.result == 2) {
answer.addClass("almost").removeAttr("disabled");
snd_wrong.play();
}
}
});
return false;
});
I uploaded sample here: http://gamoicani.es/logo/ click on any logo, I'd like to use keyboard ENTER also to submit.
// Try this!! :)
$(document).ready(function(){
$(this).on('keypress click','.unlocked figcaption .check',function(e){
if((e.type === 'keypress' && e.keyCode === 13) || e.type === 'click')
{
// All your code inside the .on()
}
});
});
You can make the ajax function external and then call it on click and keypress (enter) events like this:
$(document).on("click", ".unlocked figcaption .check", ajaxFunction);
$(document).on("keypress", "#myForm input:text", function (e) {
if (e.keyCode == 13){
e.preventDefault();
ajaxFunction();
}
});
function ajaxFunction(){
var logo_id = $(this).parent().attr("id");
var answer = $("#" + logo_id + " input[name=guesslogo]");
var logo_lang = answer.attr("data-lang");
answer.removeAttr("class").attr("disabled","true");
//Submit answer for review
$.ajax({
url: "actions.php",
get: "GET",
data: "answer=" + answer.val() + "&logo_id=" + logo_id + "&logo_lang=" + logo_lang,
cache: false,
success: function (data){
var response = jQuery.parseJSON(data);
if (response.result == 1) {
answer.addClass("correct").siblings(".clear, .hint").fadeTo("slow","0.4");
answer.parent().append('<div class="alert"><h3>Correct!</h3> <p>Score: '+ response.score +'</p></div>');
$("#" + logo_id).siblings(".logo").removeClass("logo").addClass("answered").removeAttr("style");
snd_correct.play();
//update user_score and user_level values in leaderboard and header widgets
var this_user = $("header aside").attr("data-usern");
if (this_user) {
var this_user_score = $("header aside .user_score").text();
var this_user_level = $("header aside .user_level").text();
$("[data-usern="+ this_user +"] .user_score").empty().append(parseInt(this_user_score) + parseInt(response.score));
if (response.level_up == 1) {
var new_level = parseInt(this_user_level) +1;
$("[data-usern="+ this_user +"] .user_level").empty().append(new_level);
update_view(new_level);
}
//
update_level_progress_bar();
}
} else if (response.result == 0) {
answer.addClass("wrong").removeAttr("disabled");
snd_wrong.play();
} else if (response.result == 2) {
answer.addClass("almost").removeAttr("disabled");
snd_wrong.play();
}
}
});
return false;
};
jsfiddle

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.

how should i delay the ajax request?

like this jquery code, how should i delay the ajax request? input is a text field...over my head ....thx for help...
var proname = "" ;
$("input[name='proname']").keyup(function(e){
//how should i delay this function on here ?
if (e.which == 13) return ;
if ($(this).val() != proname)
{
proname = $(this).val() ;
}
else
{
return ;
}
$.ajax({
type: "post",
data: "proname="+proname+"&page=1",
url: "/project/searchrate",
success: function(view){
alert(view) ;
}
}) ;
}) ;
You want to use setTimeout.
From your usage, it seems to be a good idea to have a timeout that is being cleared every time another keyup event occurs, to avoid a queue.
var requestDelay;
var proname;
$('input[name=proname]').keyup(function() {
if(e.which == 13 || $(this).val() == proname)
return;
proname = $(this).val();
// postpone the submit another 300 ms upon every new character
window.clearTimeout(requestDelay);
requestDelay = window.setTimeout(function() {
$.ajax(...);
}, 300);
});
I see you are doing some kind of autosearch/autocomplete feature.
Have you considered just using the jQuery UI Autocomplete? http://jqueryui.com/demos/autocomplete/#remote-jsonp
As for the question itself you have already been answered.
Use setTimeout.
var proname = "" ;
$("input[name='proname']").keyup(function(e){
if (e.which == 13) return;
setTimeout(function() {
if ($(this).val() != proname) {
proname = $(this).val();
} else {
return;
}
$.ajax({
type: "post",
data: "proname="+proname+"&page=1",
url: "/project/searchrate",
success: function(view){
alert(view) ;
}
});
}, DELAY_IN_MSECS);
});
$("input[name='proname']").keyup(function(e){
//how should i delay this function on here ?
if (e.which == 13) return ;
setTimeout(function() {
if ($(this).val() != proname)
{
proname = $(this).val() ;
}
else
{
return ;
}
$.ajax({
type: "post",
data: "proname="+proname+"&page=1",
url: "/project/searchrate",
success: function(view){
alert(view) ;
}
}) ;
}, 1000);
}) ;

Categories