Was using .bind but now haved to use .delegate... have tried .undelegate? - jquery-selectors

Heres the jsfiddle, jsfiddle.net/kqreJ
So I was using .bind no problem for this function but then I loaded more updates to the page and found out that .bind doesn't work for content imported to the page but just for content already on the page! Great!
So I switched it up to .delegate which is pretty cool but now I can't figure out how to .bind .unbind my function the way it was???
Function using .bind which worked perfect... except didn't work on ajax content.. :(
$('.open').bind("mouseup",function(event) {
var $this = $(this), handler = arguments.callee;
$this.unbind('mouseup', handler);
var id = $(this).attr("id");
var create = 'nope';
var regex = /\d+$/,
statusId = $('#maindiv .open').toArray().map(function(e){
return parseInt(e.id.match(regex));
});
var divsToCreate = [ parseInt(id) ];
$.each(divsToCreate, function(i,e)
{
if ( $.inArray(e, statusId) == -1 ) {
create = 'yup';
}
});
if( create == 'yup' ) {
if(id) {
$.ajax({
type: "POST",
url: "../includes/open.php",
data: "post="+ id,
cache: false,
success: function(html) {
$('.open').html(html);
$this.click(handler);
}
});
}
}
});
New function using .delegate that is not binded and creates multiple instances?
$('#maindiv').delegate("span.open", "mouseup",function(event) {
var $this = $(this), handler = arguments.callee;
$this.unbind('mouseup', handler);
var id = $(this).attr("id");
var create = 'nope';
var regex = /\d+$/,
statusId = $('#maindiv .open').toArray().map(function(e){
return parseInt(e.id.match(regex));
});
var divsToCreate = [ parseInt(id) ];
$.each(divsToCreate, function(i,e)
{
if ( $.inArray(e, statusId) == -1 ) {
create = 'yup';
}
});
if( create == 'yup' ) {
if(id) {
$.ajax({
type: "POST",
url: "../includes/open.php",
data: "post="+ id,
cache: false,
success: function(html) {
$('.open').html(html);
$this.click(handler);
}
});
}
}
});
I've spent hours trying to figure this out because I like learning how to do it myself but I had to break down and ask for help... getting frustrated!
I also read that when your binding and unbinding .delegate you have to put it above the ajax content? I've tried using .die() and .undelegate()... Maybe I just don't know where to place it?

Take a look at undelegate
It does to delegate what unbind does to bind.
In your case, I think it'd be something like:
$('#maindiv').undelegate("span.open", "mouseup").delegate("span.open", "mouseup" ...
Then you can drop the $this.unbind('mouseup', handler); within the function.

Related

Autopopulate field in suitecrm

I have this ajax call that populate the fields to a related field.
YAHOO.util.Event.onDOMReady(function() {
YAHOO.util.Event.addListener(
"parent_module_another_module_ida",
"change",
ajaxReq
);
function ajaxReq() {
var propertyId = $("#parent_module_another_module_ida").val();
if (propertyId != "") {
$.ajax({
url: "/?entryPoint=ajaxEntryPoint&module=Parent_Module&id=" + propertyId,
success: function(result) {
var res = JSON.parse(result);
$("#price").val(res['price']);
}
});
}
}
});
The fields gets auto populated but the format becomes something like 1000.000000 ive tried to modify the precision in its vardefs to 0 but its still the same i want to format the number if possible to something like this 1,000.
You will need to use toFixed function of javascript to get the required results.
Following is the modified code:
YAHOO.util.Event.onDOMReady(function() {
YAHOO.util.Event.addListener(
"parent_module_another_module_ida",
"change",
ajaxReq
);
function ajaxReq() {
var propertyId = $("#parent_module_another_module_ida").val();
if (propertyId != "") {
$.ajax({
url: "/?entryPoint=ajaxEntryPoint&module=Parent_Module&id=" + propertyId,
success: function(result) {
var res = JSON.parse(result);
price_val = res['price'].toFixed(0);
$("#price").val(price_val);
}
});
}
}
});

Fancybox not working with Simple Configurable Products (SCP)

I need some help with Javascript to get fancybox working with SCP. The following solution has not worked for me although I'm aware I'm missing some fundamental code. The first product image works perfectly opening the fancybox lightbox but once you select from the configurable dropdowns it changes the image which then does not call the lightbox and opens in the browser.
SCP advice is:
To fix, it's often just a matter of editing the showFullImageDiv function in the scp_product_extension.js file: Change evalScripts to true if it's not already, and possibly you'll also need to remove the code which exists in a few places which looks like: product_zoom = new Product.Zoom('image', 'track', 'handle', 'zoom_in', 'zoom_out', 'track_hint');
I tried this but it's not just a simple matter of removing "product_zoom..." my understanding is that fancybox needs to be called replace this line of code.
Original:
Product.Config.prototype.showFullImageDiv = function(productId, parentId) {
var imgUrl = this.config.ajaxBaseUrl + "image/?id=" + productId + '&pid=' + parentId;
var prodForm = $('product_addtocart_form');
var destElement = false;
var defaultZoomer = this.config.imageZoomer;
prodForm.select('div.product-img-box').each(function(el) {
destElement = el;
});
if(productId) {
new Ajax.Updater(destElement, imgUrl, {
method: 'get',
evalScripts: true,
onComplete: function() {
//Product.Zoom needs the *image* (not just the html source from the ajax)
//to have loaded before it works, hence image object and onload handler
if ($('image')){
var imgObj = new Image();
imgObj.src = $('image').src;
imgObj.onload = function() {product_zoom = new Product.Zoom('image', 'track', 'handle', 'zoom_in', 'zoom_out', 'track_hint'); };
} else {
destElement.innerHTML = defaultZoomer;
product_zoom = new Product.Zoom('image', 'track', 'handle', 'zoom_in', 'zoom_out', 'track_hint')
}
}
});
} else {
destElement.innerHTML = defaultZoomer;
product_zoom = new Product.Zoom('image', 'track', 'handle', 'zoom_in', 'zoom_out', 'track_hint');
}
};
I know I need to call fancybox in the below locations but not sure how to go about it. From what I understand fancybox is called on pageload so not sure imgObj.onload will even work?
Product.Config.prototype.showFullImageDiv = function(productId, parentId) {
var imgUrl = this.config.ajaxBaseUrl + "image/?id=" + productId + '&pid=' + parentId;
var prodForm = $('product_addtocart_form');
var destElement = false;
var defaultZoomer = this.config.imageZoomer;
prodForm.select('div.product-img-box').each(function(el) {
destElement = el;
});
if(productId) {
new Ajax.Updater(destElement, imgUrl, {
method: 'get',
evalScripts: true,
onComplete: function() {
//Product.Zoom needs the *image* (not just the html source from the ajax)
//to have loaded before it works, hence image object and onload handler
if ($('image')){
var imgObj = new Image();
imgObj.src = $('image').src;
imgObj.onload = CALL FANCYBOX
} else {
destElement.innerHTML = defaultZoomer;
CALL FANCYBOX
}
}
});
} else {
destElement.innerHTML = defaultZoomer;
CALL FANCYBOX
}
};
Unfortunately my javascript is very basic and any help on what I need to add would be gratefully received. I found a few posts with the same issue but no solution.
Thanks

Mapping List with Knockout Mapping

I have created view model
var catalog = ko.observableArray();
$.ajax({
type: "GET",
url: "http://localhost:8080/ticket-service/rest/ticket/list",
success: function(msg) {
catalog.push.apply(catalog, $.map(msg, function(data) {
return new Ticket(data)
}));
return catalog;
},
error: function(msg) {
console.log(msg)
}
});
and the model
function Ticket(data) {
this.ticketId = ko.observable(data.ticketId);
this.ticketNo = ko.observable(data.ticketNo);
this.ticketTitle = ko.observable(data.ticketTitle);
this.longDescription = ko.observable(data.longDescription);
this.createdBy = ko.observable(data.createdBy);
this.createdOn= ko.observable(data.createdOn);
this.assignTo = ko.observable(data.assignTo);
this.priority = ko.observable(data.priority);
this.dueDate = ko.observable(data.dueDate);
this.status = ko.observable(data.status);
this.projectId = ko.observable(data.projectId);
}
with at the end viewmodel like this
return {
ticket: newTicket,
searchTerm: searchTerm,
catalog: filteredCatalog,
newTicket: newTicket,
addTicket: addTicket,
delTicket: delTicket
};
})();
console.log(vm);
ko.applyBindings(vm);
produce list,add, and delete form.The question is how can i use knockout mapping that can list from get methode.
you need to do something like this
Demonstrated taking a single entity from your code .
view:
Output Preview :
<pre data-bind="text:ko.toJSON($data,null,2)"></pre>
viewModel:
function Ticket(data) {
this.ticketId = ko.observable(data.ticketId);
}
var mapping = {
create: function (options) {
return new Ticket(options.data);
}
};
var ViewModel = function () {
var self = this;
self.catalog = ko.observableArray();
var data = [{
'ticketId': 1
}, {
'ticketId': 2
}]
//under ajax call do the same but pass 'msg' in place of data
self.catalog(ko.mapping.fromJS(data, mapping)())
console.log(self.catalog()); // check console for output
};
ko.applyBindings(new ViewModel());
sample working fiddle here

how do i make a jquery plugin

I'm trying to make a jquery plugin
but it's not working what a'm i doing wrong
(function($){
$.fn.rss({
//pass the options variable to the function
rss: function(options) {
//Set the default values, use comma to separate the settings, example:
var defaults = {
feedUrl: ''
}
var options = $.extend(defaults, options);
return this.each(function() {
var Setting = options;
//code to be inserted here
$.ajax({
type: "GET",
url: Setting.feedUrl,
dataType: "xml",
success: function(xml) {
$(xml).find('channel').each(function(){
$(xml).find('image').each(function(){
var title2 = $(this).find('title').text();
var url2 = $(this).find('link').text();
$('<div class="title"></div>').html(''+title2+'').fadeIn(1000).appendTo('#title');
});
$(xml).find('item').each(function(){
var title = $(this).find('title').text();
var brief = $(this).find('description').text();
var url = $(this).find('link').text();
$('<div class="items"></div>').html('<div class="dis">'+brief+'</div>').fadeIn(1000).appendTo('#blab');
});
});
}
});
});
}
});
})(jQuery)
By writing $.fn.rss(...), you're calling a non-existent function.
You need to create a function by writing
$.fn.rss = function(...) { ... };

Refresh a ListBox in ASP.NET MVC 2 with jQuery

I've looked around on SO to see if this has been asked before and couldn't find anything (so if it has indeed been asked before then I apologize.
Here's what I'm trying to do, a user can select from a list of skills for their profile, if a skill they want isn't in the list then they can add it to the database, I have that accomplished with WCF & jQuery AJAX. Here's the code for that:
$("#AddNewSkill").click(function () {
$("#AddNewSkill").attr("disabled", true);
$("#newSkill").attr("disabled", true);
var newSkill = $("#newSkill").val();
var data = { name: $("#newSkill").val(), description: "", type: "Skill" };
data = JSON.stringify(data)
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "../WeddingPhotographerService.svc/AddNew",
data: data,
dataType: "json",
success: function () {
successCall('#newSkill', '#AddNewSkill');
//$('#SkillListViewContainer').load('../Account/GetSkillControl');
},
error: function (msg) {
$("#AddSkillError").text(msg.d);
$("#AddSkill").attr("disabled", false);
$("#NewSkill").attr("disabled", false);
}
});
});
Here's the method in the AJAX-Enabled WCF service:
[OperationContract]
public bool AddNew(string name, string description, string type)
{
switch (type)
{
case "":
goto default;
case "skill":
IRepository<Skill> skillRepo = ObjectFactory.GetInstance<IRepository<Skill>>();
var skill = new Skill { Name = name, Description = (string.IsNullOrEmpty(description)) ? string.Empty : description };
skillRepo.Save(skill);
return true;
case "equipment":
IRepository<Equipment> eqRep = ObjectFactory.GetInstance<IRepository<Equipment>>();
var eq = new Equipment { Name = name, Description = (string.IsNullOrEmpty(description)) ? string.Empty : description };
eqRep.Save(eq);
return true;
case "occasion":
IRepository<Occassion> occRepo = ObjectFactory.GetInstance<IRepository<Occassion>>();
var oc = new Occassion { Name = name, Description = (string.IsNullOrEmpty(description)) ? string.Empty : description };
occRepo.Save(oc);
return true;
default:
IRepository<Skill> repo = ObjectFactory.GetInstance<IRepository<Skill>>();
var s = new Skill { Name = name, Description = (string.IsNullOrEmpty(description)) ? string.Empty : description };
repo.Save(s);
return true;
}
}
It's kind of ugly but I'll optimize it once I have this 2nd part working. Here's how the ListBox is being loaded in the view:
<%: Html.ListBox("Skills", Model.SkillList, new { #style = "width:157px; height:90px;background:#e2f0f1;", #size = "3", #class = "inputbox" })%>
Which comes from RegistrationModelView.cs, here's SkillList in my model view:
private MultiSelectList GetSkills(string[] selectedValues)
{
List<Skill> list = new List<Skill>();
IRepository<Skill> skills = ObjectFactory.GetInstance<IRepository<Skill>>();
foreach (Skill skill in skills.GetAll())
{
list.Add(new Skill()
{
Key = skill.Key,
Name = skill.Name,
Description = ""
});
}
return new MultiSelectList(list, "Key", "Name", selectedValues);
}
And the action in AccountController.cs that loads the view
[MoveFormsScript]
public ActionResult Index()
{
return View(new RegistrationModelView());
}
I'm pretty sure all the code I posted (other than how the new item is added with the WCF service and the jQuery for consuming said service is irrelevant but I thought I'd offer as much information as possible).
Like I said the new value is added to the database no problem, my issue is updating the ListBox to reflect the new values. Anyone got any ideas and can help with this?
Well I mucked around until I found something that does what I need it to do. It may not be the most efficient or elegant way to accomplish the task but it at least works (Maybe someone will come along with a different solution some day).
What I ended up doing was make another $,ajax() call in the success of the first call like this
$("#AddNewSkill").click(function () {
$("#AddNewSkill").attr("disabled", true);
$("#newSkill").attr("disabled", true);
var data = { name: $("#newSkill").val(), description: "", type: "skill" };
data = JSON.stringify(data)
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "../WeddingPhotographerService.svc/AddNew",
data: data,
dataType: "json",
success: function () {
$.ajax({
type:"POST",
datatype:"json",
url: "../Account/GetSkills",
success:updateSkillsListBox
});
},
error: function (msg) {
alert(msg.d);
}
});
});
function updateSkillsListBox(data, status) {
$("#Skills").html("");
for(var d in data) {
$("<option value=\"" + data[d].Value + "\">" + data[d].Name + "</option>").appendTo("#Skills");
}