Setup jqueryui before element is rendered - javascript

In creating a table cells with very cool options I need to take two steps. First I create the table cell as a DOM object in javascript with all the 'normal' functionality, like is it a checkbox, a select, an input, a link, etc.
Then I need to put the table on the page to do the next step, which I consider advanced functionality like jqueryui's autocomplete and date select. It is awesome to have these drop downs for the user.
I do have this working, however, I do need to make two calls. The first to createTableCell, then I render, then I need to make another call to postRenderTableFunctions to get the autocomplete functionality working. So the question is, why the second call, what is it about jqueryui that will not work on the first call. You can see the commented section under input creation where I tried to get the autocomplete working.
function createTableCell(name, td_def)
{
var cell=document.createElement('td');
if(td_def['type'] == 'date')
{
var element = document.createElement('input');
element.name = name;
element.id = name;
cell.appendChild(element);
$('#' + element.id).datepicker(
{
dateFormat: 'yy-mm-dd',
onSelect: function ()
{
$(this).focus();
},
onClose: function (dateText, inst)
{
$(this).select();
}
});
}
else if(td_def['type'] == 'checkbox')
{
element = document.createElement('input');
element.type = 'checkbox';
element.name = name;
element.id = name;
/*if(this.tdo[r][td_def['db_field']]['data'] == 1)
{
element.checked = true;
}*/
cell.appendChild(element);
}
else if (td_def['type'] == 'select')
{
element = document.createElement('select');
element.name = name;
element.id = name;
var option = document.createElement('option');
option.value = 'NULL';
option.appendChild(document.createTextNode("Select..."));
element.appendChild(option);
for (var j in td_def['select_names'])
{
option = document.createElement('option');
option.value = td_def['select_values'][j];
option.appendChild(document.createTextNode(td_def['select_names'][j]));
element.appendChild(option);
}
cell.appendChild(element);
}
else if (td_def['type'] == 'tree_select')
{
element = document.createElement('select');
element.id = name;
element.name = name;
var option = document.createElement('option');
option.value = 'NULL';
option.appendChild(document.createTextNode("Select..."));
element.appendChild(option);
var level = 0;
//console.log(td_def['select_array']);
this.addNestedSelectOptions(element, td_def['select_array'], level);
if (typeof td_def['properties'] !== 'undefined')
{
for (var index in td_def['properties'])
{
eval('element.' + index + '= ' + td_def['properties'][index] + ';');
}
}
cell.appendChild(element);
}
else if (td_def['type'] == 'input')
{
element = document.createElement('input');
element.type = 'text';
element.id = name;
element.name = name;
cell.appendChild(element);
/*
if(typeof td_def['autoComplete'] != 'undefined')
{
console.log('attempting Autocomplete');
$( "#" + name ).autocomplete({
source: function( request, response )
{
$.ajax(
{
url: td_def['autoComplete']['url'],
type: 'GET',
async: true,
data:
{
ajax_request: td_def['autoComplete']['ajax_request'],
featureClass: "P",
style: "full",
maxRows: 12,
search_terms: request.term
},
success: function( data )
{
console.log(data);
parsed_autocomplete_data = parseJSONdata(data);
response( parsed_autocomplete_data);
}
});
},
search: function()
{
// custom minLength
var term = this.value;
//console.log(term);
if(typeof td_def['minLength'] != 'undefined')
{
var minL = td_def['minLength'];
}
else
{
var minL = 1;
}
if ( term.length < minL )
{
return false;
}
},
focus: function()
{
// prevent value inserted on focus
return false;
},
open: function(event, ui)
{
var dialog = $(this).closest('.ui-dialog');
if(dialog.length > 0){
$('.ui-autocomplete.ui-front').zIndex(dialog.zIndex()+1);
}
},
select: function( event, ui )
{
selected_autocomplete_index = $.inArray(ui.item.value, parsed_autocomplete_data);
}
});
}
*/
}
else if (td_def['type'] == 'textarea')
{
element = document.createElement('TEXTAREA');
element.id = name;
element.name = name;
cell.appendChild(element);
}
else if (td_def['type'] == 'td')
{
cell.innerHTML = 'TBD';
cell.name = name;
cell.id = name;
}
else
{
alert(td_def['type'] + ' have not coded that.....');
}
return cell;
function addNestedSelectOptions(element, category_array, level)
{
for (var key in category_array)
{
option = document.createElement('option');
option.value = key;
name = category_array[key]['name'];
for(i=0;i<level;i++)
{
name = "\u00A0" + name;
name = "\u00A0" + name;
}
option.appendChild(document.createTextNode(name));
element.appendChild(option);
if(!$.isEmptyObject(category_array[key]['children']))
{
addNestedSelectOptions(element, category_array[key]['children'], level+1);
}
}
}
}
//this function needs to be called separately.
function postRenderTableFunctions(table_div_id, table_def)
{
//extra jquery functionality -- needs to go after stuff is rendered
for(var i=0;i<table_def.length;i++)
{
if(typeof table_def[i]['autoComplete'] != 'undefined')
{
var id = table_div_id + '_' + table_def[i]['db_field'];
console.log(id);
//is the auto complete open?
/*$("#" + id ).bind('autocompleteopen', function(event, ui)
{
$(this).data('is_open',true);
});
$("#" + id ).bind('autocompleteclose', function(event, ui)
{
$(this).data('is_open',false);
});*/
/*$( "#" + id ).bind( "keydown", function( event )
{
//what is this for ?
if ( event.keyCode === $.ui.keyCode.TAB && $(this).data('is_open') )
{
event.preventDefault();
}
if ( event.keyCode === $.ui.keyCode.ENTER && !$(this).data('is_open'))
{
//do what?
}
});*/
var i2 = i;
var me = table_def;
$( "#" + id ).autocomplete({
source: function( request, response )
{
$.ajax(
{
url: me[i2]['autoComplete']['url'],
type: 'GET',
async: true,
data:
{
ajax_request: me[i2]['autoComplete']['ajax_request'],
featureClass: "P",
style: "full",
maxRows: 12,
search_terms: request.term
},
success: function( data )
{
console.log(data);
parsed_autocomplete_data = parseJSONdata(data);
response( parsed_autocomplete_data);
}
});
},
search: function()
{
// custom minLength
var term = this.value;
//console.log(term);
if(typeof table_def[i2]['minLength'] != 'undefined')
{
var minL = table_def[i2]['minLength'];
}
else
{
var minL = 1;
}
if ( term.length < minL )
{
return false;
}
},
focus: function()
{
// prevent value inserted on focus
return false;
},
open: function(event, ui)
{
var dialog = $(this).closest('.ui-dialog');
if(dialog.length > 0){
$('.ui-autocomplete.ui-front').zIndex(dialog.zIndex()+1);
}
},
select: function( event, ui )
{
selected_autocomplete_index = $.inArray(ui.item.value, parsed_autocomplete_data);
}
});
}
}
}

My original comment to your question -
I suspect i may work if you replace
$( "#" + name ).autocomplete({
with
$(element).autocomplete({
though I don't currently have means to test it.
My response -
Basically using $("#name") looks for an element with the ID name in the DOM. When you are running your code element has not been added to the DOM yet so the autocomplete cannot be attached to to your element.
Surrounding element with $() converts it to a jQuery variable which you can attach the autocomplete to before it is added to the DOM.

Related

Wordpress enqueue jquery not working

I installed an plugin on my current clean wordpress installation. However I always get the following error as soon as the widget for the plugin gets laoded
TypeError: $ is not a function
I checked the js files for the addon and they all seem to make proper use of jQuery instead of $ also the register_script function requires jquery as dependency
Below you can see the add_action function
if (!is_admin()) {
function woocommerce_ogonecw_add_frontend_css() {
wp_register_style('woocommerce_ogonecw_frontend_styles', plugins_url('resources/css/frontend.css', __FILE__));
wp_enqueue_style('woocommerce_ogonecw_frontend_styles');
true);
wp_register_script('ogonecw_frontend_script', plugins_url('resources/js/frontend.js', __FILE__), array(
'jquery'
));
wp_enqueue_script('ogonecw_frontend_script');
wp_localize_script('ogonecw_frontend_script', 'woocommerce_ogonecw_ajax',
array(
'ajax_url' => admin_url('admin-ajax.php')
));
}
add_action('wp_enqueue_scripts', 'woocommerce_ogonecw_add_frontend_css');
frontend.js looks like this
jQuery(function (jQuery) {
var isSubmitted = false;
var CheckoutObject = {
cssClass: '',
successCallback: '',
placeOrder: function() {
var form = jQuery('form.checkout');
var form_data = form.data();
// WGM: Back Button
if(jQuery("input[name=cw-wgm-button-back]").length > 0) {
return true;
}
//WGM: MultiStep
if(jQuery("input[name=wc_gzdp_step_submit]").length > 0) {
if(jQuery("input[name=wc_gzdp_step_submit]").val() == "address"){
return true;
}
}
var selectedPaymentMethodElement = jQuery('input:radio[name=payment_method]:checked');
var selectedPaymentMethod = selectedPaymentMethodElement.val();
var secondRun = false;
if(jQuery("input[name=ogonecw_payment_method_choice]").length > 0) {
secondRun = true;
selectedPaymentMethodElement = jQuery("input[name=ogonecw_payment_method_choice]");
selectedPaymentMethod = selectedPaymentMethodElement.val();
}
var moduleName = 'ogonecw';
var selectedModuleName = (selectedPaymentMethod != undefined) ?
selectedPaymentMethod.toLowerCase().substring(0, moduleName.length) : '';
onOgoneCwCheckoutPlaceObject = this;
if (moduleName == selectedModuleName) {
form.addClass('processing');
if ( form_data["blockUI.isBlocked"] != 1 ) {
form.block({
message: null,
overlayCSS: {
background: '#fff',
opacity: 0.6
}
});
}
this.successCallback = previewAuthorization;
this.cssClass = 'ogonecw-preview-fields';
onOgoneCwCheckoutPlaceObject = this;
if(secondRun) {
this.generateOrder(form, selectedPaymentMethod);
return false;
}
var validateFunctionName = 'cwValidateFields'+selectedPaymentMethod.toLowerCase();
var validateFunction = window[validateFunctionName];
if (typeof validateFunction != 'undefined') {
validateFunction(function(valid){onOgoneCwCheckoutPlaceObject.successCall();}, function(errors, valid){onOgoneCwCheckoutPlaceObject.failureCall(errors, valid);});
return false;
}
onOgoneCwCheckoutPlaceObject.successCall();
return false;
}
},
failureCall: function(errors, valid){
alert(errors[Object.keys(errors)[0]]);
var form = jQuery('form.checkout');
form.removeClass('processing').unblock();
form.find( '.input-text, select, input:checkbox' ).trigger( 'validate' ).blur();
},
successCall : function(){
var form = jQuery('form.checkout');
var selectedPaymentMethodElement = jQuery('input:radio[name=payment_method]:checked');
var selectedPaymentMethod = selectedPaymentMethodElement.val();
onOgoneCwCheckoutPlaceObject = this;
if(selectedPaymentMethodElement.parents('li').find('.ogonecw-validate').length > 0){
var ajaxUrl;
if(typeof wc_checkout_params != 'undefined') {
ajaxUrl = wc_checkout_params.ajax_url;
}
if(typeof checkoutUrl == 'undefined') {
ajaxUrl = woocommerce_params.ajax_url;
}
var separator = ajaxUrl.indexOf('?') !== -1 ? "&" : "?";
ajaxUrl = ajaxUrl+separator+"action=woocommerce_ogonecw_validate_payment_form";
var inputData = getFormFieldValues('ogonecw-preview-fields', selectedPaymentMethod.toLowerCase());
var postData = "&";
jQuery.each(inputData, function(key, value) {
postData += encodeURIComponent(key)+"="+encodeURIComponent(value)+"&";
});
jQuery.ajax({
type: 'POST',
url: ajaxUrl,
data: form.serialize()+postData+ onOgoneCwCheckoutPlaceObject.cssClass + "=true",
success: function( code ) {
var response = '';
try {
response = jQuery.parseJSON(code);
if ( response.result == 'success' ) {
onOgoneCwCheckoutPlaceObject.generateOrder(form, selectedPaymentMethod);
return false;
}
else if ( response.result == 'failure' ) {
throw 'Result failure';
} else {
throw 'Invalid response';
}
}
catch(err ){
// Remove old errors
jQuery( '.woocommerce-error, .woocommerce-message' ).remove();
// Add new errors
if ( response.message ) {
form.prepend(response.message);
} else {
form.prepend(code);
}
// Cancel processing
form.removeClass( 'processing' ).unblock();
// Lose focus for all fields
form.find( '.input-text, select, input:checkbox' ).trigger( 'validate' ).blur();
// Scroll to top
jQuery( 'html, body' ).animate({
scrollTop: ( jQuery( 'form.checkout' ).offset().top - 100 )
}, 1000 );
}
},
dataType: 'html'
});
return false;
}
else {
onOgoneCwCheckoutPlaceObject.generateOrder(form, selectedPaymentMethod);
return false;
}
},
generateOrder: function(form, selectedPaymentMethod) {
onOgoneCwCheckoutPlaceObject = this;
var checkoutUrl;
if(typeof wc_checkout_params != 'undefined') {
checkoutUrl = wc_checkout_params.checkout_url;
}
if(typeof checkoutUrl == 'undefined') {
checkoutUrl = woocommerce_params.checkout_url;
}
jQuery.ajax({
type: 'POST',
url: checkoutUrl,
data: form.serialize() + "&" + onOgoneCwCheckoutPlaceObject.cssClass + "=true",
success: function( code ) {
var response = '';
try {
if (code.indexOf("<!--WC_START-->") >= 0) {
code = code.split("<!--WC_START-->")[1];
}
if (code.indexOf("<!--WC_END-->") >= 0) {
code = code.split("<!--WC_END-->")[0];
}
try {
// Check for valid JSON
response = jQuery.parseJSON( code );
} catch ( e ) {
// Attempt to fix the malformed JSON
var validJson = code.match( /{"result.*"}/ );
if ( null === validJson ) {
throw 'Invalid response';
} else {
response = jQuery.parseJSON(validJson[0]);
}
}
if ( response.result == 'success' ) {
onOgoneCwCheckoutPlaceObject.successCallback(response, selectedPaymentMethod);
}
else if ( response.result == 'failure' ) {
throw 'Result failure';
} else {
throw 'Invalid response';
}
}
catch( err ) {
if ( response.reload === 'true' ) {
window.location.reload();
return;
}
// Remove old errors
jQuery( '.woocommerce-error, .woocommerce-message' ).remove();
// Add new errors
if ( response.messages ) {
form.prepend( response.messages );
} else {
form.prepend( code );
}
// Cancel processing
form.removeClass( 'processing' ).unblock();
// Lose focus for all fields
form.find( '.input-text, select, input:checkbox' ).trigger( 'validate' ).blur();
// Scroll to top
jQuery( 'html, body' ).animate({
scrollTop: ( jQuery( 'form.checkout' ).offset().top - 100 )
}, 1000 );
// Trigger update in case we need a fresh nonce
if ( response.refresh === 'true' ) {
jQuery( 'body' ).trigger( 'update_checkout' );
}
jQuery( 'body' ).trigger( 'checkout_error' );
}
},
dataType: 'html'
});
},
};
var getFormFieldValues = function(parentCssClass, paymentMethodPrefix) {
var output = {};
jQuery('.' + parentCssClass + ' *[data-field-name]').each(function (element) {
var name = jQuery(this).attr('data-field-name');
if(name.lastIndexOf(paymentMethodPrefix, 0) === 0) {
name = name.substring(paymentMethodPrefix.length);
name = name.substring(1, name.length -1 );
if(this.type == "radio") {
if(this.checked) {
output[name] = jQuery(this).val();
}
}
else{
output[name] = jQuery(this).val();
}
}
});
return output;
};
var generateHiddenFields = function(data) {
var output = '';
jQuery.each(data, function(key, value) {
output += '<input type="hidden" name="' + key + '" value="' + value + '" />';
});
return output;
};
var removeNameAttributes= function(cssClass) {
// Remove name attribute to prevent submitting the data
jQuery('.' + cssClass + ' *[name]').each(function (element) {
jQuery(this).attr('data-field-name', jQuery(this).attr('name'));
if(jQuery(this).is(':radio')){
return true;
}
jQuery(this).removeAttr('name');
});
}
var addAlias = function(cssClass){
// Add listener for alias Transaction selector
jQuery('.' + cssClass).parents('li').find('.ogonecw-alias-input-box > select').bind('change', function() {
jQuery('body').trigger('update_checkout');
});
}
var registerCheckoutObject = function(){
bindOrderConfirmEvent(CheckoutObject);
};
var bindOrderConfirmEvent = function (CheckoutObject) {
var form = jQuery('form.checkout');
var attached = form.attr('data-ogonecw-attached');
if (attached != 'true') {
form.attr('data-ogonecw-attached', 'true');
form.bind('checkout_place_order', function() {
return CheckoutObject.placeOrder();
});
return false;
}
};
// We have to make sure that the JS in the response is executed.
jQuery( document ).ready(function() {
if (typeof window['force_js_execution_on_form_update_listener'] === 'undefined') {
window['force_js_execution_on_form_update_listener'] = true;
jQuery('body').bind('updated_checkout', function() {
removeNameAttributes('ogonecw-preview-fields');
addAlias('ogonecw-preview-fields');
if (jQuery('.ogonecw-preview-fields').length > 0) {
registerCheckoutObject();
}
});
}
});
jQuery( document ).ajaxStop(function(event, xhr, settings) {
removeNameAttributes('ogonecw-preview-fields');
addAlias('ogonecw-preview-fields');
if (jQuery('.ogonecw-preview-fields').length > 0) {
registerCheckoutObject();
}
});
var previewAuthorization = function (result, selectedPaymentMethod) {
if(typeof result.redirect !== 'undefined') {
var additionalFields = jQuery('<div class="ogonecw-preview-fields" style="display: none;"></div>');
jQuery('.' + 'ogonecw-preview-fields' + ' *[data-field-name]').each(function (element) {
var name = jQuery(this).attr('data-field-name');
if(name.lastIndexOf(selectedPaymentMethod.toLowerCase(), 0) === 0) {
jQuery(additionalFields).append(jQuery(this));
}
});
var redirectUrl;
if ( result.redirect.indexOf( "https://" ) != -1 || result.redirect.indexOf( "http://" ) != -1 ) {
redirectUrl = result.redirect;
} else {
redirectUrl = decodeURI( result.redirect );
}
jQuery.get(redirectUrl, function(data){
var newBodyString = data.replace(/^[\S\s]*<body[^>]*?>/i, "").replace(/<\/body[\S\s]*jQuery/i, "");
var newBody = jQuery("<div></div>").html(newBodyString);
if(newBody.find('.wgm-go-back-button').length > 0){
jQuery('body').html(newBody.html());
jQuery('form.checkout').append(additionalFields);
jQuery('form.checkout').append('<input type="hidden" name="ogonecw_payment_method_choice" value="'+selectedPaymentMethod+'"/>');
jQuery('.wgm-go-back-button').on('click', function() {
jQuery('form.checkout').append('<input type="hidden" name="cw-wgm-button-back" value="back"/>');
});
jQuery('form.checkout').on('submit', function(){
return CheckoutObject.placeOrder();
});
jQuery("html, body").animate({
scrollTop: jQuery("form.checkout").offset().top - 100
}, 1e3);
}
else {
window.location = decodeURI( redirectUrl );
}
});
}
else if(typeof result.ajaxScriptUrl !== 'undefined'){
jQuery.getScript(result.ajaxScriptUrl, function() {
eval("var callbackFunction = " + result.submitCallbackFunction);
callbackFunction(getFormFieldValues('ogonecw-preview-fields', selectedPaymentMethod.toLowerCase()));
});
}
else {
var newForm = '<form id="ogonecw_preview_form" action="' + result.form_action_url + '" method="POST">';
newForm += result.hidden_form_fields;
newForm += generateHiddenFields(getFormFieldValues('ogonecw-preview-fields', selectedPaymentMethod.toLowerCase()));
newForm += '</form>';
jQuery('body').append(newForm);
jQuery('#ogonecw_preview_form').submit();
}
}
});
So what exactly is causing this error since the plugin seems to be setup correctly

Too much recursion - jquery - autocomplete

So here is my autocomplete functionality:
var selected;
var itemAdded = false;
$('.js-main-search').autocomplete({
minLength: 3,
source: function(request, response) {
$.getJSON('/dashboard/searchDocumentsAndCompanies.do',
{ q: request.term},
function(data) {
if(data.length == 0){
data = [
{name: 'No matches found', resultType: 'COMPANY', noResults: true},
{name: 'No matches found', resultType: 'BRANCHES', noResults: true},
];
}
data.unshift({name: 'Search from documents ยป', reqQuery: request.term, docSearch:true});
response(data);
});
},
select: function( event, ui ) {
event.preventDefault();
selected = true;
if(ui.item.docSearch && !itemAdded){
$(".textbox.ui-front li:eq(1)").before('<li class="search-category ui-menu-item">Documents</li>');
itemAdded = true;
}
}
});
$('.js-main-search').data("uiAutocomplete").close = function(event) {
if (!selected){
$('.js-main-search').data("uiAutocomplete").close.apply( this, arguments );
}
selected = false;
};
$('.js-main-search').data('uiAutocomplete')._renderItem = function( ul, item ) {
itemAdded = false;
item.value = item.name;
var $el = $( "<li>" ).append(item.value);
if(item.docSearch){
$el.addClass( "search-documents-btn" );
$el.one('click', function (e) {
e.preventDefault();
console.log(ul.children());
});
}
if(!item.noResults && !item.docSearch){
$el.append('<div class="meta">Documents | Company page</div>');
}
$el.appendTo( ul );
return $el;
};
$('.js-main-search').data('uiAutocomplete')._renderMenu = function(ul, items) {
var companiesResults = true;
var branchesResults = true;
var that = this,currentCategory = '';
$.each(items, function(index, item) {
var li;
if (item.resultType != currentCategory && !item.docSearch) {
var categoryTitle = '';
if(item.resultType == 'COMPANY'){
categoryTitle = 'Companies';
companiesResults = false;
} else{
categoryTitle = 'Branches'
branchesResults = false;
}
ul.append('<li class="search-category">'+categoryTitle+'</li>');
currentCategory = item.resultType;
}
li = that._renderItemData(ul, item);
if (item.resultType) {
item.value = item.name;
li.attr('aria-label', item.resultType + ' : '+ item.value);
}
});
if(companiesResults && branchesResults){
ul.append('<li class="search-show-more-btn">Show more</li>');
}
};
When I am starting to enter search keyword sometimes it gives me the following error in console: "Too much recursion", but I don't understand why.
Any suggestions are welcome.
Usually when you get a stack overflow error, it is because you have a recursion for which no exit condition exist or is triggered. Looking at your code, here's the function that causes the problem.
$('.js-main-search').data("uiAutocomplete").close = function (event) {
if (!selected) {
$('.js-main-search').data("uiAutocomplete").close.apply(this, arguments);
}
selected = false;
};
I guess the selected = false; should be inside the if statement before the recursive call like so:
$('.js-main-search').data("uiAutocomplete").close = function (event) {
if (!selected) {
selected = false;
$('.js-main-search').data("uiAutocomplete").close.apply(this, arguments);
}
};

How to handle execution of javascript in infinite scroll?

I am using infinite scroll to load posts and tried to integrate a custom like button for every single posts that needs a small jquery script to work. My problem is I added this Jquery directly after the sucess in ajax load posts. But when I load eg the 3. page my jquery script executes twice and on the posts of the 2nd page the lke buttons are not working correctly. How can I handle this? If I dont execute the code after the ajax request and only call this jquery code globally the like buttons do not work in the new loaded posts of the ajax infinite scroll. Maybe I need to stop the sript of before when eg loadin 3. page through the ajax infinite scroll but how? This is my code:
function load_more_posts(selector){
var url = $(selector).attr('href');
var data;
loading = true;
$.ajax({
url: url,
data: data,
success: function( data ) {
var $items = $( '.loading-content .item', data );
$new_anchor = $( selector, data );
$items.addClass('hidden');
if ( $('#cooked-plugin-page .result-section.masonry-layout .loading-content').length ){
$( '.loading-content').isotope( 'insert', $items );
} else {
$( '.loading-content').append($items);
setTimeout(function() {
$items.removeClass('hidden');
}, 200);
}
if($new_anchor.length) {
$(selector).attr('href', $new_anchor.attr('href'));
} else {
$(selector).remove();
}
loading = false;
$('.like-btn').each(function() {
var $button = $(this),
$icon = $button.find('> i'),
likedRecipes = $.cookie('cpLikedRecipes'),
recipeID = $button.attr('data-recipe-id');
cookied = $button.attr('data-cookied');
userLiked = $button.attr('data-userliked');
if ( cookied == 1 && typeof likedRecipes !== 'undefined' && likedRecipes.split(',').indexOf(recipeID) > -1 || userLiked == 1 ) {
$icon.removeClass('fa-heart-o').addClass('fa-heart');
}
});
$('#cooked-plugin-page .like-btn').on('click', function() {
var $button = $(this),
$icon = $button.find('> i'),
$count = $button.find('.like-count'),
count = parseInt($count.text()),
likedRecipes = $.cookie('cpLikedRecipes'),
recipeID = $button.attr('data-recipe-id'),
cookied = $button.attr('data-cookied'),
likeURL = $button.attr('href'),
likeAction;
if ( $icon.hasClass('fa-heart-o') ) {
$icon.removeClass('fa-heart-o').addClass('fa-heart');
count++;
if (cookied == 1){
if ( typeof likedRecipes === 'undefined' ) {
likedRecipes = recipeID;
} else {
likedRecipes = likedRecipes + ',' + recipeID;
}
$.cookie('cpLikedRecipes', likedRecipes, { expires: 365 } );
}
likeAction = 'like';
} else {
$icon.removeClass('fa-heart').addClass('fa-heart-o');
count--;
if (cookied == 1){
if ( typeof likedRecipes === 'undefied' ) {
return false;
}
}
if (cookied == 1){
var likedSplit = likedRecipes.split(','),
recipeIdx = likedSplit.indexOf(recipeID);
if ( recipeIdx > -1 ) {
likedSplit.splice( recipeIdx, 1 );
likedRecipes = likedSplit.join(',');
$.cookie('cpLikedRecipes', likedRecipes, { expires: 365 } );
likeAction = 'dislike';
}
} else {
likeAction = 'dislike';
}
}
$.ajax({
'url' : likeURL,
'data': {
'action' : 'cp_like',
'likeAction': likeAction
},
success: function(data) {
$count.text(data);
}
});
return false;
});
$('#cooked-plugin-page .tab-links a').on('click', function() {
var tab = $(this).attr('href');
if ( !$(this).is('.current') ){
$(this).addClass('current').siblings('.current').removeClass('current');
$('#cooked-plugin-page.fullscreen .tab').removeClass('current');
$(tab).addClass('current');
$win.scrollTop(0);
}
return false;
});
if($('.rating-holder').length) {
$('.rating-holder .rate')
.on('mouseenter', function() {
var $me = $(this);
var $parent = $me.parents('.rating-holder');
var my_index = $me.index();
var rated = $parent.attr('data-rated');
$parent.removeClass(function(index, css) {
return (css.match (/(^|\s)rate-\S+/g) || []).join(' ');
});
$parent.addClass('rate-' + (my_index + 1));
})
.on('mouseleave', function() {
var $me = $(this);
var $parent = $me.parents('.rating-holder');
var my_index = $me.index();
var rated = $parent.attr('data-rated');
$parent.removeClass(function(index, css) {
return (css.match (/(^|\s)rate-\S+/g) || []).join(' ');
});
if(rated !== undefined) {
$parent.addClass('rate-' + rated);
}
})
.on('click', function() {
var $me = $(this);
var $parent = $me.parents('.rating-holder');
var my_index = $me.index();
$('.rating-real-value').val(my_index + 1);
$parent.attr('data-rated', my_index + 1);
$parent.addClass('rate-' + (my_index + 1));
});
}
setTimeout(function() {
masonry();
}, 500);
}
});
}
There's a great plugin for scrolling. He has methods such as bund, unbind, destroy and e.t.c.:
https://github.com/infinite-scroll/infinite-scroll#methods

how to add submit function to js Onclick function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
i am trying to trigger a url when click on a button, when click on the delete button it triggers the JS Alert but it is not passing the link, it removes the button instead. how can make it process the link once i confirm the alert?
js code
<script>
$(function() {
$('#demo').confirmOn('click', function() {
$(this).remove();
});
});
</script>
html
<a href="index.php?page=test:delete&item_id={item_id}" id="demo">
<input type="button" class="log_button" value="Delete"/>
ConfirmOn code..
(function($) {
var confirmOn = $.confirmOn = {};
confirmOn.providedOptions = {};
confirmOn.defaultSettings = {
questionText: 'Are you sure?',
classPrepend: 'confirmon',
textYes: 'Yes',
textNo: 'No'
};
confirmOn.overrideDefaultSettings = function(settings) {
confirmOn.defaultSettings = $.extend({}, confirmOn.defaultSettings, settings);
};
confirmOn.setOptions = function($element, options) {
options = $.extend({}, confirmOn.defaultSettings, options);
$element.data('confirmon', {
options: options
});
};
confirmOn.createOverlay = function($element) {
var classPrepend = $element.data('confirmon').options.classPrepend;
return $('<div/>').addClass(classPrepend + '-overlay').hide().appendTo('body');
};
confirmOn.showOverlay = function($element) {
var classPrepend = $element.data('confirmon').options.classPrepend;
$('.' + classPrepend + '-overlay').fadeIn();
};
confirmOn.deleteOverlay = function($element) {
var classPrepend = $element.data('confirmon').options.classPrepend;
$('.' + classPrepend + '-overlay').fadeOut(function(){
$(this).remove();
});
};
confirmOn.createBox = function($element) {
var classPrepend = $element.data('confirmon').options.classPrepend;
var questionText = $element.data('confirmon').options.questionText;
var textYes = $element.data('confirmon').options.textYes;
var textNo = $element.data('confirmon').options.textNo;
var $box = $('<div/>').addClass(classPrepend + '-box').hide().appendTo('body');
$('<p class="' + classPrepend + '-content"/>')
.html(questionText)
.appendTo($box);
$('<button class="' + classPrepend + '-button ' + classPrepend + '-button--yes"/>')
.html(textYes)
.appendTo($box);
$('<button class="' + classPrepend + '-button ' + classPrepend + '-button--no"/>')
.html(textNo)
.appendTo($box);
$('.' + classPrepend + '-button').on('keydown', function(e){
if (e.which === 9) { //Tab key
e.preventDefault();
$('.' + classPrepend + '-button').not(this).focus();
}
});
};
confirmOn.showBoxAndFocusNo = function($element) {
var classPrepend = $element.data('confirmon').options.classPrepend;
$('.' + classPrepend + '-box').fadeIn(function(){
$(this).children('button').eq(1).focus();
});
};
confirmOn.deleteBox = function($element) {
var classPrepend = $element.data('confirmon').options.classPrepend;
$('.' + classPrepend + '-box').fadeOut(function(){
$(this).remove();
});
};
$.confirmOn.handleEscKey = function($element) {
$(document).on('keydown.confirmon.close', function(e){
if (e.which === 27) { //Esc key
$.confirmOn.deleteOverlay($element);
$.confirmOn.deleteBox($element);
$(document).off('keydown.confirmon.close');
}
});
}
confirmOn.convertArguments = function(options, events, selector, data, handler) {
if (typeof options === 'object') {
$.each(options, function(key, val) {
if (typeof val === 'string') { //Options provided so shift all args to left
confirmOn.providedOptions = options;
options = events;
events = selector;
selector = data;
data = handler;
return false;
} else { //No options
confirmOn.providedOptions = {};
}
});
} else {
confirmOn.providedOptions = {};
}
if (selector == null && data == null && handler == null) {
//(events[S], handler)
selector = events;
events = options;
} else if (data == null && handler == null) {
//(events[S], selector, handler)
//(events[S], data, handler)
data = selector;
selector = events;
events = options;
} else {
handler = data;
data = selector;
selector = events;
events = options;
}
if (typeof events === 'object') {
//Implementation .on( events [, selector ] [, data ] )
return {
events: events,
selector: selector,
data: data
};
} else {
//Implementation .on( events [, selector ] [, data ], handler(eventObject) )
return {
events: events,
selector: selector,
data: data,
handler: handler
};
}
};
$.confirmOn.attachHandlers = function($element, handler, event) {
var classPrepend = $element.data('confirmon').options.classPrepend;
$('.' + classPrepend + '-box button').eq(0).on('click', function(){
$.confirmOn.deleteOverlay($element);
$.confirmOn.deleteBox($element);
handler.call($element.get(), event, true); //Call the handler function. the TRUE parameter indicates that the user pressed the YES button
});
$('.' + classPrepend + '-box button').eq(1).on('click', function(){
$.confirmOn.deleteOverlay($element);
$.confirmOn.deleteBox($element);
handler.call($element.get(), event, false); //Call the handler function. the FALSE parameter indicates that the user pressed the YES button
});
};
$.fn.confirmOn = function(options, events, selector, data, handler) {
var userHandler;
if (typeof events === 'function') {
userHandler = events;
events = confirmHandler;
} else if (typeof selector === 'function') {
userHandler = selector;
selector = confirmHandler;
} else if (typeof data === 'function') {
userHandler = data;
data = confirmHandler;
} else if (typeof handler === 'function') {
userHandler = handler;
handler = confirmHandler;
}
var $element = $(this);
var onArgs = $.confirmOn.convertArguments(options, events, selector, data, handler);
$.confirmOn.setOptions($element, $.confirmOn.providedOptions);
$element.on(onArgs.events, onArgs.selector, onArgs.data, onArgs.handler);
function confirmHandler(event) {
event.preventDefault();
$.confirmOn.createOverlay($element);
$.confirmOn.showOverlay($element);
$.confirmOn.createBox($element);
$.confirmOn.showBoxAndFocusNo($element);
$.confirmOn.handleEscKey($element);
$.confirmOn.attachHandlers($element, userHandler, event);
};
};
}(jQuery));
Use confirm():
Try this:
$("#demo").click(function() {
var confirm1 = confirm('Dialogue');
if (confirm1) {
$(this).remove();
return true;
} else {
return false;
}
});
UPDATE
$(function () {
$('#demo').confirmOn('click', function (e, confirmed) {
if (confirmed) { // Clicked yes
document.location.href= $(this).attr('href');
$(this).remove();
$('#msg_button_1').remove();
} else { // Clicked no
$('#msg_button_1').fadeIn();
}
});
});
JSFiddle Demo
Edited
<script>
$(function() {
$('.log_button').confirmOn('click', function(e, confirmed) {
if(confirmed){
//$('#demo').remove();
$('#demo').click();
}else{
alert("not go");
}
});
});
</script>
is this the thing that you actually want to do? click the button and then go to the link?

JQuery AutoComplete Append to Open List

I tested the JQuery autocomplete UI widget and noticed that the autocomplete has extremely poor performance in IE when dealing with large amount of data. My client uses internet explorer 7.
I found a solution to mitigate the performance issue. Instead of returning all the matches of the autocomplete search I only return the first 40 matches. Code below
source: function (request, response) {
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term), "i");
var select_el = select.get(0); // get dom element
var rep = new Array(); // response array
var maxRepSize = 40; // maximum response size
// simple loop for the options
var looper = 0;
for (var i = 0; i < select_el.length; i++) {
var text = select_el.options[i].text;
if (!request || request == '') {
// add element to result array
rep[looper++] = {
label: text,
value: text,
option: select_el.options[i]
};
}
else if ( select_el.options[i].value && matcher.test(text) ) {
// add element to result array
rep[looper++] = {
label: text,
value: text,
option: select_el.options[i]
};
}
if ( rep.length > maxRepSize ) {
needMoreItems = true;
break;
}
}
// send response
response( rep );
},
The client asked me to append a "More Results" item to the autocomplete list. If there were more than 40 items that matched the search the "More Results" item would appear of at the bottom of the list. If a user clicked on the "More Results" item, the autocomplete drop down would expand to include the next 40 matches. I experimented with the jQuery autocomplete and I was able to populate the auto suggest list with the next 40 items but when the user clicked on one of the dynamically added items, I could not bind the click event to the Select Event of the autocomplete UI widget. Code below:
open: function( event, ui ) {
if (needMoreItems) {
needMoreItems = false;
$('<li class="ui-menu-item" role="menuitem" id="yoADDMORE" ><a class="ui-corner-all" tabindex="-1">... more available<br/><br/></a></li>')
.bind({
click: function(e) {
var appendHtml = '';
var select_el = select.get(0);
var maxRepSize = 40; // maximum response size
// simple loop for the options
var looper = 0;
for (var i = 41; i < select_el.length; i++) {
appendHtml += '<li class="ui-menu-item" role="menuitem"><a class="ui-corner-all" tabindex="-1">' + select_el.options[i].text + '</a></li>';
if ( looper ++ > maxRepSize ) {
needMoreItems = true;
break;
}
}
if (needMoreItems)
appendHtml += '<li class="ui-menu-item" role="menuitem" id="yoADDMORE" ><a class="ui-corner-all" tabindex="-1">... more available<br/><br/></a></li>';
$('#yoADDMORE').remove();
$('ul.ui-autocomplete').html($('ul.ui-autocomplete').html() + appendHtml);
$('ul.ui-autocomplete > li')
.bind({
mouseenter: function(e) {
// Hover event handler
$("> a",this).attr('class','ui-corner-all ui-state-hover');
},
mouseleave: function(e) {
// Hover event handler
$("> a",this).attr('class','ui-corner-all');
}
});
},
mouseenter: function(e) {
// Hover event handler
$("> a",this).attr('class','ui-corner-all ui-state-hover');
},
mouseleave: function(e) {
// Hover event handler
$("> a",this).attr('class','ui-corner-all');
}
})
.appendTo('ul.ui-autocomplete');
}
},
Links to jsFiddle
http://jsfiddle.net/eyecode/sX4Ba/
Any help would be appreciated.
Thanks in Advance
In order to list the top 20 options with a "More .." at the bottom of the first 20 items. Once a user presses "More .." link. All the items will be displayed in the drop down.
(function ($) {
$.widget("ui.typeaheadtextbox", {
_create: function () {
var self = this,
select = this.element.hide(),
theWidth = select.width(),
selected = select.children(":selected"),
value = selected.val() ? selected.text() : "";
var _searchItem = '';
var _more = false;
var _lastIndex = 0;
var _maxSize = 20;
var _rep = null;
var input = this.input = $("<input id='" + select[0].id + "_jq' style=\"width: " + theWidth + "px\">")
.insertAfter(select)
.val(value)
.autocomplete({
delay: 10,
minLength: 0,
source: function (request, response) {
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term), "i");
var j = 0;
_rep = response;
_searchItem = request.term;
var select_el = select.get(0); // get dom element
var rep = new Array(); // response array
for (var i = 0; i < select_el.length; i++) {
var text = select_el.options[i].text;
if (select_el.options[i].value && (!request.term || matcher.test(text))) {
j++;
if (j > _maxSize) {
_more = true;
_lastIndex = i;
break;
}
// add element to result array
rep[(j - 1)] = {
label: text.replace(new RegExp("^(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(_searchItem) + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>"), value: text, option: select_el.options[i]
};
}
}
return response(rep);
},
autoFocus:true,
open: function(event, ui) {
if (_more) {
_more = false;
$('<li class="ui-menu-item_more" role="menuitem" id="' + select.get(0).id + '_ADDMORE_' + _lastIndex + '" ><a class="ui-corner-all" tabindex="-1"><img width="16" src="Content/themes/base/images/icon-search-small.png"/> <strong>View All</strong></a></li>')
.bind({
click: function(e) {
var response = _rep;
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(_searchItem), "i");
var select_el = select.get(0); // get dom element
var rep = new Array(); // response array
var j = 0;
for (var i = 0; i < select_el.length; i++) {
var text = select_el.options[i].text;
if (select_el.options[i].value && (!_searchItem || matcher.test(text))) {
// add element to result array
rep[j++] = {
label: text.replace(new RegExp("^(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(_searchItem) + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>"), value: text, option: select_el.options[i]
};
}
}
$(this).remove();
return _rep(rep);
},
mouseenter: function(e) { $("> a",this).attr('class','ui-corner-all ui-state-hover'); },
mouseleave: function(e) { $("> a",this).attr('class','ui-corner-all');}
})
.appendTo('ul.ui-autocomplete');
_lastIndex = 0;
return true;
}
},
select: function (event, ui) {
ui.item.option.selected = true;
self._trigger("selected", event, {
item: ui.item.option
});
},
change: function (event, ui) {
if (!ui.item) {
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i"),
valid = false;
select.children("option").each(function () {
if ($(this).text().match(matcher)) {
this.selected = valid = true;
return false;
}
});
if (!valid) {
// remove invalid value, as it didn't match anything
$(this).val("");
select.val("");
input.data("autocomplete").term = "";
return false;
}
}
}
})
.addClass("ui-widget ui-widget-content ui-corner-all");
input.data("autocomplete")._renderMenu = function( ul, items ) {
var self = this; var htm = ''; var beginHtm = '<li><a>'; var endHtm = '</a></li>';
for(var i=0;i<items.length;i++) {
htm += beginHtm + items[i].label + endHtm;
}
ul[0].innerHTML = htm;
var liTags = ul[0].getElementsByTagName('li');
for(var i=0;i<liTags.length;i++) {
$(liTags[i]).data("item.autocomplete", items[i]);
}
return true;
};
},
destroy: function () {
this.input.remove();
this.element.show();
$.Widget.prototype.destroy.call(this);
},
clear: function () {
this.element.val("");
this.input.val("");
}
});
})(jQuery);

Categories