I have 2 separate javascript functions, the first builds a dropdown list from a JSON feed and then the second fires the Selectric plugin to style the dropdown.
I added a delay to the plugin function but it's a hack so id like to add this function after the get request finishes.
$(document).ready(function() {
$.get('scanlistjson',{id:''},function(responseJson) {
var $select = $('#scanlist');
$.each(responseJson, function(key, value) {
$('<option>').val(key).text(value).appendTo($select);
});
});
});
setTimeout(function() {
$('#scanlist').selectric();
}, 300);
You have to call it in the $.get call back function after appending the all option of select:
$(document).ready(function() {
$.get('scanlistjson',{id:''},function(responseJson) {
var $select = $('#scanlist');
$.each(responseJson, function(key, value) {
$('<option>').val(key).text(value).appendTo($select);
});
$('#scanlist').selectric(); // call it here
});
});
Put the function call inside callback.
$(document).ready(function() {
$.get('scanlistjson',{id:''},function(responseJson) {
var $select = $('#scanlist');
$.each(responseJson, function(key, value) {
$('<option>').val(key).text(value).appendTo($select);
});
$('#scanlist').selectric();
});
});
Related
I am trying to loop through elements which are returned as dynamically loaded content via the ajax $.post method. Here is the code:
$.post(ajax_url, {action: 'filter-search-results', term_id: term_id}, function (res) {
$('.job_listings').empty();
$('.job_listings').html(res);
$('.hotel-rate').each(function (i, obj) {
//...
But the each function is not being executed.
When I trigger a click event of body it works:
$.post(ajax_url, {action: 'filter-search-results', term_id: term_id}, function (res) {
$('.job_listings').empty();
$('.job_listings').html(res);
$(document).on('click', 'body', function() {
$('.hotel-rate').each(function (i, obj) {
//...
It works fine. But I don't want to the each to be binded in any event. How can I execute the each function without triggering any event?
Why don't you try this:
var items = $('.hotel-rate');
$.each(items, function (index, value) {........
just like it is explained in the jQuery API documentation
Have you tried looping through the job listings object after it's populated?
$.post(ajax_url, {action: 'filter-search-results', term_id: term_id}, function (res) {
var $jobs = $('.job_listings').html(res);
$jobs.find('.hotel-rate').each(function (i, obj) {
//...
I am trying to pass $(this) value to a jQuery function. The function is below but does not work. There are no errors in console.
The function is firing because when I place an alert at the top it works.
(function($){
$.fn.calculateHours = function() {
var tbody = $(this).closest('tbody'); // get closest tbody
var table = $(this).closest('table'); // get closest table
var params = table.find('.disguise').serialize(); // parameters
$.ajax({
type: 'post',
dataType: 'json',
url: '/calculateHours',
data: params,
success: function (response) {
// loop over object
$.each(response.rows, function(index, array) {
$.each(array, function(key, value) {
$('#row_' + index).find('.' + key).html(value);
});
});
if($.isPlainObject(response.columns)) {
$.each(response.columns, function(day, hour) {
$('.totalsRow').find('.total_' + day).html(hour);
});
}
$('.totalsRow').find('.grand_total').html(response.grand_total);
}
});
}
})(jQuery);
$(document).on('change', '.disguise', function(e) {
$.fn.calculateHours();
});
Adding functions to $.fn is meant to extend the jQuery object. In other words, you should be calling .calculateHours on your jQuery object:
$(document).on('change', '.disguise', function(e) {
$(this).calculateHours();
});
You want jquery to set the context automatically. To do that just pass a reference to the function as the handler.
$(document).on('change', '.disguise', $.fn.calculateHours);
I use query to build a mobile app. First of all I use $.getJSON to retrieve data from json file:
$.getJSON('js/sura.json', function(data){
$.each(data, function(key, value){
//alert(key+' '+value['id']);
buildList(value['id'], value['name'], value['number']);
});
});
There are more than 100 rows from json file.
After that, I need to put every lists to an elements name <ul id="list></ul>. Should I make new Javascript function then write the code:
function buildList(id, name, number){
var name_elm = '<h3>'+name+'</h3>';
var noq_elm = '<span>'+number+'</span>';
var $list_elm = '<li>'+name_elm+''+noq_elm+'</li>';
$('#list').append($list_elm);
}
After I use .append(...). I would like to add click listener to every lists (each list has unique id).
How should I write query to add listener to each <li></li>?
You can use event delegation:
var $list_elm = '<li class="noqele">'+name_elm+''+noq_elm+'</li>';
$('#list').append($list_elm);
}
And Code for click event:
$(document).on('click','.noqele',function(){
//click event code...
});
This can be done more efficiently like this
$.getJSON('js/sura.json', function (data) {
var container = $();
$.each(data, function (key, value) {
var h3 = $('<h3 />', {text : value.name}),
span = $('<span />', {text : value.number}),
li = $('<li />', {
id: value.id,
on: {
click: click_function
}
});
container = container.add(li.append(h3, span));
});
$('#list').append(container);
});
function click_function() {
// do stuff on click
}
function getData(url) {
$.getJSON(url, function(result) {
$('#formNav ul').append('<ul/>')
$.each(result, function() {
var list = $('#formNav li'),
listItem = $('<li/>'),
html = listItem.append($('<h5/>').text(this.name));
$.each(this.items, function() {
listItem.append($('<a />').attr('href', this.id).text(this.name))
});
list.append(html)
});
});
};
$(function(){
var Menu = {
$menu: $('.config-nav #formNav'),
$trades : $(".config-nav select#tradesmanList"),
$skills : $(".config-nav select#jobList"),
init: function(){
var $menu = Menu.$menu;
// Set menu up
$menu.children("li").addClass('closed');
$menu.find(".js-reveal").hide();
Menu.$skills.attr("disabled", "disabled");
Menu.$trades.on("change", function($skills){
Menu.$skills.removeAttr("disabled");
});
// bind to click on the item...
$menu.on("click", "h4", this.toggle);
},
toggle: function() {
// Toggle the hide show of the drill down menu
var $this = $(this),
$category = $this.parent();
console.log($this.parent().index());
var data = getData("test.json");
$category.addClass("loading").toggleClass("open");
$this.next(".reveal").delay(100).toggle(0, function(){
$category.Data;
$category.removeClass("loading");
});
}
};
Menu.init();
});
I have a function that returns json data , i then call this function in the Menu function to display the data however every time i click the button the data just keeps being generated instead i want it to display the data and then once it is clicked again hide the data? if anyone has any advice that would be great.
Thanks.
When ever you call the toggle function You seem to get the data using
var data = getData("test.json"); and then use it to populate the list..
Why don't you move the getData method to outside the toggle function and instead move it to to init function .. Look's like it should be fine then..
I'm currently writing a JQuery plugin that loads colors from a JSON web service into a drop down list.
The drop down list background-color changes according to the selected value. For the most part it is working. on any regular change it works as expected, the problem I am having is on the initial page load I am using triggerHandler("change"); and it triggers but I seem to be getting an undefined error on the selected value from the drop down list on page load so it doesn't trigger the color change on the drop down list
My code is:
$.fn.bindColorsList = function (options) {
var defColor = options.defaultColor;
var svcUrl = options.svcurl;
//var f_target = options.filterTarget;
var $this = this;
$.ajax({
url: options.svcurl,
dataType: 'json',
/*data: { filter: src_filt },*/
success: function (fonts) { fillcolors(fonts, $this) },
error: function () { appendError(f_target, "colors failed to load from server") }
});
this.on("change", function (event) {
log($(event.target).attr("id") + " change detected");
//change ddl dropdown color to reflect selected item ;
var hcolor = $this.find('option:selected').attr("name");
$this.attr("style", "background-color:" + hcolor);
});
function fillcolors(colors, target) {
$(target).empty();
$.each(colors, function (i, color) {
$(target).append("<option name='"+color.HexValue+"' value='" + color.Name + "' style='background-color:"+color.HexValue+"'>"+color.Name+"</option>");
});
};
//in a seperate file
$(document).ready(function () {
$("#dd-font-color").bindColorsList({ svcurl: "/home/colors"});
$("#dd-back-color").bindColorsList({ svcurl: "/home/colors" });
});
You are doing an AJAX request to populate your dropdown which, by the way, is an asynchronous one. In this case you need to trigger the event in the success callback of the AJAX request.
var $this = this;
// Bind the onchange event
$this.on("change", function (event) {
..
});
// Populate using AJAX
$.ajax({
...
success: function (fonts) {
// Populate the values
fillcolors(fonts, $this);
// Trigger the event
$this.trigger("change");
},
...
});
That's it.