i have some dynamic data that gets appended to a list and any links in that data doesnt seem to work.
i am using jquery 1.8.3 and on() should account for the live method, i think
setInterval(function () {
getNot();
}, 2000);
function getNot() {
var data = {
t1: 'test1',
t2: 'test2',
t3: 'test3'
};
var size = 0,
li = '';
$.each(data, function (k, v) {
li += '<li>' +
'<a href="#" class="add" data-listid="' + k + '">' +
'<h2>load data - ' + k + '</h2>' +
'</a>' +
'</li>';
size++;
});
var but = $('#not'),
ul = $('#not_ul');
but.find('span').text(size + ' Notifications');
ul.html(li);
ul.listview().listview("refresh");
}
// this doesn't seem to work
$('.add').on("click", function () {
var listId = $(this).data('listid');
console.log(listId);
return false;
});
see full example here
any ideas on this issue?
$('.add').on("click", function () {
You need to pass a selector to make on generate a delegate event:
$('#{containerId}').on("click", '.add', function () {
var listId = $(this).data('listid');
console.log(listId);
return false;
});
containerId should be the closest static element to the dynamic created .adds elements.
Related
I have a problem that when i choose from Select, it will show option with formatSelection that i have configed BUT when i set selected value for Select that didn't get data object variable formatRepoSelectionLanguage from data_selection
function setSelect2Data(id, data_id = null, data_text = null, data_image = null, data_description = null, data_path = null, data_select = ""){
/*
id: selection class or ID of component has use Select2
data_id: id
data_text: text
data_image: image
data_path: path
data_description: description
data_select: String HTML Selection
*/
var data_selection = {
id : data_id||null,
text : data_text||null,
image : data_image||null,
path : data_path||null,
description: data_description||null
}
$(id)
.empty()
.append(data_select);
//$(id).select2('data' ,data_selection);
$(id).append(data_selection).trigger('change');
$(id).trigger({
type: 'select2:select',
params: {
object: data_selection,
formatSelection: formatRepoSelectionLanguage(data_selection),
formatResult: formatRepoLanguage(data_selection)
}
});
}
This is formatRepoLanguage:
function formatRepoLanguage (repo) {
if (repo.loading) {
return repo.text;
}
var $container = $(
"<div class='select2-result-language clearfix'>" +
"<div class='select2-result-language__icon'><img src='" + base_url_icon + repo.image + "' /></div>" +
"<div class='select2-result-language__meta'>" +
"<div class='select2-result-language__title'></div>" +
"<div class='select2-result-language__description'></div>" +
"</div>" +
"</div>"
);
$container.find(".select2-result-language__title").text(repo.text);
$container.find(".select2-result-language__description").text(repo.path)
return $container;
}
This is formatRepoSelectionLanguage:
function formatRepoSelectionLanguage (state) {
if (!state.id) {
return state.text;
}
var $state = $(
'<span id = "language_'+ state.id +'"><img class="img-flag" /> <span></span></span>'
);
// Use .text() instead of HTML string concatenation to avoid script injection issues
$state.find("span").text(state.text);
$state.find("img").attr("src", base_url_icon + state.image);
return $state;
}
I have try to set data like a string to option element and it works! Actually i think it's a bug of Select2 and i'm using version 4.0.13 and now i recognize that i don't need to use select2 function coz it takes data from option element which i have append into select element! That's my answer for my question if anyone have good idea please tell me! Thanks for your time!
I have a page where I am adding jquery-ui autocompletes dynamically
My .autocomplete() code includes a $.getJSON('my_url', my_payload) where, in my_payload,' I am trying to send the request.term (what I typed into the jqueryui textbox) as well as the id of the jquery ui text box.
The problem is, for all the dynamically added textboxes, they were just picking up the term and id of the original autocomplete.
I managed to find a way to get the id of the added (not original) autocomplete by wrapping the autocomplete in a function that has the added field passed in as a parameter, but because the 'term' is in the request, which comes from .autocomplete, I do not know how to get this for the new ones.
https://jsfiddle.net/amchugh89/1L8jvea5/4/
//=======dynamic formset script from https://medium.com/all-about-
django/adding-forms-dynamically-to-a-django-formset-375f1090c2b0======
function updateElementIndex(el, prefix, ndx) {
var id_regex = new RegExp('(' + prefix + '-\\d+)');
var replacement = prefix + '-' + ndx;
if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex, replacement));
if (el.id) el.id = el.id.replace(id_regex, replacement);
if (el.name) el.name = el.name.replace(id_regex, replacement);
}
function cloneMore(selector, prefix) {
var newElement = $(selector).clone(true);
var total = $('#id_' + prefix + '-TOTAL_FORMS').val();
newElement.find(':input:not([type=button]):not([type=submit]):not([type=reset])').each(function() {
if ($(this).attr('name')){
var name = $(this).attr('name').replace('-' + (total-1) + '-', '-' + total + '-');
var id = 'id_' + name;
$(this).attr({'name': name, 'id': id}).val('').removeAttr('checked');
if($(this).attr('id').includes('gl')){
console.log($(this).attr('id'))
make_autocomplete($(this))
}
}
});
newElement.find('label').each(function() {
var forValue = $(this).attr('for');
if (forValue) {
forValue = forValue.replace('-' + (total-1) + '-', '-' + total + '-');
$(this).attr({'for': forValue});
}
});
total++;
$('#id_' + prefix + '-TOTAL_FORMS').val(total);
$(selector).after(newElement);
var conditionRow = $('.form-row:not(:last)');
conditionRow.find('.btn.add-form-row')
.removeClass('btn-success').addClass('btn-danger')
.removeClass('add-form-row').addClass('remove-form-row')
.html('<span class="glyphicon glyphicon-minus" aria-hidden="true"></span>');
return false;
}
function deleteForm(prefix, btn) {
var total = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val());
if (total > 1){
btn.closest('.form-row').remove();
var forms = $('.form-row');
$('#id_' + prefix + '-TOTAL_FORMS').val(forms.length);
for (var i=0, formCount=forms.length; i<formCount; i++) {
$(forms.get(i)).find(':input').each(function() {
updateElementIndex(this, prefix, i);
});
}
}
return false;
}
$(document).on('click', '.add-form-row', function(e){
e.preventDefault();
cloneMore('.form-row:last', 'form');
return false;
});
$(document).on('click', '.remove-form-row', function(e){
e.preventDefault();
deleteForm('form', $(this));
return false;
});
//====================
//AUTOCOMPLETE==(that allows for multiple ACs
https://stackoverflow.com/questions/24656589/using-jquery-ui-autocomplete-
with-multiple-input-fields)===================================
function make_autocomplete(ee) {
ee.on("focus", function(){ //.autocomplete({
$(this).autocomplete({
minLength: 2,
source: function( request, response ) {
var term = request.term;
//with the formset, I want to get the row for which I am typing in the
'term'
var this_formset_row_autocomplete_id
=ee.attr('id');//$(this.element).prop("id");//
$(this).attr('id');
console.log(this_formset_row_autocomplete_id);
var corresponding_branch_html_id =
this_formset_row_autocomplete_id.replace('gl_account','branch');
var this_formset_row_branch_sym_id =
$('#'+corresponding_branch_html_id).val();
//console.log(corresponding_branch_html_id, this_formset_row_branch_sym_id)
var appended_data={term:term,
this_formset_row_branch_sym_id:this_formset_row_branch_sym_id};
console.log(appended_data);
$.getJSON( "{% url 'dashapp:account_autocomplete' %}", appended_data,
function( data,
status, xhr ) {
//cache[ term ] = data;
response( data );
});
}
});
});
}//end function make_autocomplete
var ee =$( ".account_autocomplete" )
make_autocomplete(ee)
//===============
You may want to try to make it more simple for testing. Something like:
function make_autocomplete(obj) {
obj.autocomplete({
minLength: 2,
source: function(req, resp) {
var myData = {
term: req.term,
original_form_branch_id: $(this).closest("form").attr("id"),
this_formset_row_branch_sym_id: $(this).closest(".row").find("select").val()
}
$.getJSON("myurl", myData, function(results) {
resp(results);
});
}
});
}
Fiddle: https://jsfiddle.net/Twisty/pywb9nhv/23/
This uses .closest() to gather details from the relative objects. Also I do not see any benefit to initializing Autocomplete on focus event.
If you would like further help, please provide Example Data that can be used in a working example.
Hope that helps a little.
I have a google map with a load of markers on it, each corresponding to a different post in the html. Each marker id is the same as each post id. Inside the map initialize = function() {... I have the following code (I'm using gon to pass info from rails to javascript):
for (m = 0; m < gon.markers.length; m++) {
marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(gon.markers[m].lat, gon.markers[m].lng),
icon: image,
infowindow: gon.markers[m].infowindow,
id: gon.markers[m].id
});
google.maps.event.addListener(marker, 'mouseover', function() {
var image = $("#map-canvas").data('marker2');
this.setIcon(image);
// console.log("marker.id: " + marker.id);
// console.log("this.id" + this.id);
$('#' + marker.id).css('background', 'red');
});
google.maps.event.addListener(marker, 'mouseout', function() {
var image = $("#map-canvas").data('marker1');
this.setIcon(image);
$('#' + marker.id).css('background', 'white');
});
markers[markers.length] = marker;
}
Uncommenting the console.log lines demonstrates that it is the classic closure problem (marker.id always has the same value no matter which marker is hovered on).
My question is, how do I code it properly so it does as intended? I just can't get the code right now matter what I try. I've tried stuff like this but is just doesn't work:
marker.on('mouseover', noticeHover(marker.id));
function noticeHover(id) {
var image = $("#map-canvas").data('marker2');
this.setIcon(image);
$('#' + id).css('background', 'gainsboro');
}
Wrap the entire code that handles the marker-creation into a function and pass the items inside the loop as argument to this function:
for (m = 0; m < gon.markers.length; m++) {
//anonymous,self-executing function
(function(props){
var goo = google.maps,
marker = new goo.Marker({
map: map,
position: new goo.LatLng(props.lat,
props.lng),
icon: image,
infowindow: props.infowindow,
id: props.id
});
goo.event.addListener(marker, 'mouseover', function() {
var image = $("#map-canvas").data('marker2');
this.setIcon(image);
$('#' + marker.id).css('background', 'red');
});
goo.event.addListener(marker, 'mouseout', function() {
var image = $("#map-canvas").data('marker1');
this.setIcon(image);
$('#' + marker.id).css('background', 'white');
});
markers.push(marker);
}(
gon.markers[m]//pass current loop-item as argument
));
}
Am trying out google fusion table queries ….
I can’t seem to use aggregate functions or Upper() etc… it works fine without them.
error: "Could not parse query".
http://jsfiddle.net/leebasky/j7kok7yz/
google.setOnLoadCallback(drawTable);
function drawTable() {
var opts = {sendMethod: 'auto'};
var query = new google.visualization.Query('https://www.google.com/fusiontables/gvizdata?&tq=', opts);
query.setQuery('SELECT col0 as test, upper(col2) from 1198pzojwSFwuyeL8hsrmKYVHNLdNsB44bxecZYs0 limit 10');
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var table = new google.visualization.Table(document.getElementById('table_div'));
table.draw(data, {showRowNumber: true});
}
As mentioned in the comment, the desired functions are currently not available.
But when you only want to apply a different format for the data this may be achieved.
The uppercase may be done via CSS text-transform: uppercase.
The YEAR you may get via a date-formatter :{pattern: 'yyyy'}
google.setOnLoadCallback(drawTable);
function drawTable() {
var opts = {
sendMethod: 'auto'
};
var query = new google.visualization.Query('https://www.google.com/fusiontables/gvizdata?&tq=', opts);
query.setQuery('SELECT col0 as test, col2 from 1198pzojwSFwuyeL8hsrmKYVHNLdNsB44bxecZYs0 limit 10');
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var formatter = new google.visualization.DateFormat({
pattern: 'yyyy'
});
formatter.format(data, 0);
var table = new google.visualization.Table(document.getElementById('table_div'));
table.draw(data, {
showRowNumber: true
});
}
#table_div tbody tr td:nth-child(3){
text-transform: uppercase;
}
<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1.1','packages':['table']}]}"></script>
<div id="table_div"></div>
I am trying to show loading message ...... I am working on single page application in phonegag using jquery mobile.
$(document).delegate("#cartaxvalidityPage", "pageinit", function () {
$.mobile.showPageLoadingMsg();
createCarTaxValidPage();
$.mobile.hidePageLoadingMsg();
});
function createCarTaxValidPage() {
var buyerList = carHaatDatabaseParsed.BuyerList;
$("#buyer-listview").empty();
for (var i = 0; i < buyerList.length; i++) {
var listItem = $('<li> </li>');
var listAnc = $('<a> </a>');
var carImag = "<img " + "src='" + "data:image/jpg;base64," + buyerList[i].BuyerPhoto + "'/>";
var listHeader = $('<h3> ' + "Buyer Name: " + buyerList[i].BuyerName + ' </h3>');
var listParagraph = $('<p> Buyer Id: ' + buyerList[i].BuyerTaxId + ' </p>');
var listParagraphValidDate = $('<p> Tax Expire Date: ' + buyerList[i].CarValidityDate + '</p>');
listAnc.append(carImag);
listAnc.append(listHeader);
listAnc.append(listParagraph);
listAnc.append(listParagraphValidDate);
listItem.append(listAnc);
$("#buyer-listview").append(listItem);
}
$("#buyer-listview").listview("refresh");
}
It doesn't show any message.
.delegate is deprecated and replaced with .on.
$(document).on("pageinit", "#cartaxvalidityPage", function () { });
On pageinit event, use setTimeout to dela showing loading message.
setTimeout(function () {
$.mobile.loading("show");
}, 10);
Use $.mobile.loading("show") and $.mobile.loading("hide")
Demo