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..
Related
So i have a modal that pops up, it makes an ajax call and gives me 3 variables back to show. In the modal there is a save button and cancel button, if the save button is clicked i want to make another ajax call to save the variables in the database.
My problem is after the modal is open i cannot check if the save button is hit because then i can pass the variable. Maybe there is a way to pass the variables to the onclick so i can take it out of this function.
$(document).on("click", '.assignButton', function (event) {
var assID = this.id;
var tempNum = assID.substring(7);
var dropdata = 'tempID=' + tempNum;
$.ajax({
type: "POST",
url: "showAssignInfo.php",
data: dropdata,
success: function (data) {
var rowArray = data.split("%!");
var teID = rowArray[0];
var teName = rowArray[1];
var coName = rowArray[2];
$("#t1").html(teID);
$("#t2").html(teName);
$("#t3").html(coName);
}
});
$('#assignModal').trigger('openModal');
$(document).on("click", '.assignSave', function (event) {
//Make ajax call with teID, teName, coName
alert("save button is clicked.");
});
});
You can get the values using the text() method:
$("#t1").text();
$("#t2").text();
$("#t3").text();
$(document).on("click", '.assignSave', function(event)
{
//Use these values in your ajax call
$("#t1").text();
$("#t2").text();
$("#t3").text();
alert("save button is clicked.");
});
1.I am not sure that I understand you, but you can try it:
$(document).on("click", '.assignButton', function(event)
{
var assID = this.id;
var tempNum = assID.substring(7);
var dropdata= 'tempID='+tempNum;
var teID, teName, coName;
$.ajax({
type:"POST",
url: "showAssignInfo.php",
data:dropdata,
success: function(data) {
var rowArray = data.split("%!");
teID = rowArray[0];
teName = rowArray[1];
coName = rowArray[2];
$("#t1").html(teID);
$("#t2").html(teName);
$("#t3").html(coName);
}
});
$('#assignModal').trigger('openModal');
$(document).on("click", '.assignSave', function(event)
{
//Here we can use teID, teName, coName
alert("save button is clicked.");
});
});
We moved that variables to the higher scope
2.In other way you need to trigger 'openModal' with extraParameters. You can read about it here.
When clicking on a list item, does it go out of scope when going into the getJSON section where I want to go and get data from a database?
I have a list of items displaying colours. Each list item has an ID set to that of a SKU. When I click on a list item, it must go and get data from the database for that SKU and populate the contents on the page.
I was playing around with some code and for interest's sake I wanted to see if I could change the text of the clicked on list item. So after the JSON call is done, I tried to set the text, but nothing happened.
I get the sku of the clicked on list item like this:
var sku = this.id;
After I do the JSON call I tried to set the text of this clicked on list item like this:
this.text('sample text');
I even tried:
this.Text('sample text');
Here is my full JavaScript/jQuery code:
<script>
$(document).ready(function () {
$('.attributes li').click(function () {
var url = 'www.example.com/test-url';
var sku = this.id;
$.getJSON(url, { sku: sku }, function (data) {
// This does not work
this.Text('sample text');
});
});
});
</script>
Here is my HTML markup:
<ul class="list-inline attributes selectable">
<li id="sku0001">Blue</li>
<li id="sku0002">Green</li>
<li id="sku0003">Red</li>
<li id="sku0004">Yellow</li>
</ul>
When going into the getJSON section does the this go out of focus? Does the clicked on list item go out of scope?
Yes!! When it gets into .getJSON, this will loose its context and this will refer to callback function of $.getJSON and will no more be referring to li. I would suggest to create an instance of this outside $.getJSON like var that=this and then assign that.text inside $.getJSON
Example:
$(document).ready(function () {
$('.attributes li').click(function () {
var that=this;
var url = 'www.example.com/test-url';
var sku = this.id;
$.getJSON(url, { sku: sku }, function (data) {
// this here does not work because it refers to callback function
that.text('sample text'); //assign with that referred previously
});
});
});
Alternatively, if you are using ajax you add an extra option called context to refer this anywhere inside the ajax
$('.attributes li').click(function () {
var url = 'www.example.com/test-url';
var sku = this.id;
$.ajax({
url : url,
dataType : 'json',
data:{sku:sku},
context : this, //add this
complete : function (data) {
// 'this' will be what you passed as context
$(this).text('sample text')
}
});
});
I have an HTML table which uses jQuery DataTables (https://datatables.net/). The rows are rendered with html links to delete a row. I have used the following code to handle the click event of link, delete the row on the server and then animate deletion of the row on the front end.
$(document).on("click", ".delete-operation", function (e) {
e.preventDefault();
var oTable = $('#alloperations').dataTable();
var operationId = $(this).data('id');
// Get the parent table row and mark it as having been selected
// due to the fact rowindex does not work in order in datatables
var tableRow = $(e.toElement).parents('tr').addClass('row_selected');
bootbox.confirm("Are you sure?", function (answer) {
if (answer) {
// send request to delete operation with given id.
$.ajax({
type: 'delete',
url: "/operations/" + operationId,
success: function () {
var anSelected = fnGetSelected(oTable);
//Get all the row cells and animate a deletion
tableRow.children().animate({ backgroundColor: "red", color: "black" }, 300, function() {
tableRow.fadeOut(2000, function() {
oTable.fnDeleteRow(anSelected[0]);
});
});
},
error: function(result) {
$("#messageContainer").html(result.responseJSON.ResponseView);
}
});
return true;
}
else {
// User clicked cancel
return true;
}
});
});
QUESTION: This works perfectly in Chrome but does not work at all in Firefox, does anyone know how I would get it to work in Firefox as well?
You should use the cross browser property 'target' of event object:
var tableRow = $(e.target).parents('tr').addClass('row_selected');
I'm having a problem with the click events not working using a Javascript MVC Controller.
TEST.Assignments.AssignmentsController = function (element) {
var elements = {
activeAssignmentsPanel: $('#lpn-activeAssignments_Cont'),
assignmentViewLink: $("#lpn-activeAssignments_Cont table tr th a")
};
var _this = this;
var model = new TEST.Assignments.AssignmentModel();
this.buildAssignmentsList = function () {
var assignments = model.getActiveAssignmentsList({
assignmentMode: "active",
mock: true,
success: function (data) {
dust.render("ActiveAssignmentsPanel", data, function(err, out) {
elements.activeAssignmentsPanel.append(out);
});
}
});
};
this.getAssignmentDetails = function(assignmentId) {
console.log(assignmentId);
};
//bind all events
elements.assignmentViewLink.click(function (e) {
console.log("blah");
console.log($(this).data("assignmentKey"));
});
};//end assignments controller
$(function () {
var assignmentsController = new TEST.Assignments.AssignmentsController();
assignmentsController.buildAssignmentsList();
});
If you look at the //bind events, I have a click function there that should be working. But it is not. The constructor is being called and the elements are traced out correctly. Any idea why the click event won't work?
I assume the assignmentViewLink elements are created and appended in the success callback. If so, it looks like a sequence problem. When you bind the click event, the assignmentViewLink elements have not been created yet, and hence, the click eventhandler isn't attached.
//bind all events
// assignmentViewLink is empty []
elements.assignmentViewLink.click(function (e) {
console.log("blah");
console.log($(this).data("assignmentKey"));
});
To verify this, move the elements.assignmentViewLink(...) into the success callback.
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.