call the function in function of custom library in Javascript - javascript

I have a library which looks like the following
(function (bindDropdownAndSetValue) {
function allFunction() {
function bindDropDownValue(response, dropdownObject) {
$.each(response, function (i, e) {
$('#' + dropdownObject.id).append('<option value=' + e[dropdownObject.value] + '>' + e[dropdownObject.text] + '</option>');
});
}
function dropdownValues(id, value, text) {
this.id = id;
this.value = value;
this.text = text;
}
}
bindDropdownAndSetValue.allFunction = allFunction;
} (bindDropdownAndSetValue));
in the above example when I call bindDropdownAndSetValue.allFunction I want to excess the functions inside allFunction but it didn't appear to work
and when I changed the library to like the following
(function (bindDropdownAndSetValue) {
function bindDropDownValue(response, dropdownObject) {
$.each(response, function (i, e) {
$('#' + dropdownObject.id).append('<option value=' + e[dropdownObject.value] + '>' + e[dropdownObject.text] + '</option>');
});
}
function dropdownValues(id, value, text) {
this.id = id;
this.value = value;
this.text = text;
}
bindDropdownAndSetValue.bindDropDownValue = bindDropDownValue;
bindDropdownAndSetValue.dropdownValues = dropdownValues;
} (bindDropdownAndSetValue));
this works fine, but the problem here is that I need to right extra line of code, to assign function one by one to bindDropdownAndSetValue.
Is there any other better way to right this code?

Keep it short and simple:
bindDropdownAndSetValue.bindDropDownValue = function(response, dropdownObject) {
$.each(response, function (i, e) {
$('#' + dropdownObject.id).append('<option value=' + e[dropdownObject.value] + '>' + e[dropdownObject.text] + '</option>');
});
};
bindDropdownAndSetValue.dropdownValues = function(id, value, text) {
this.id = id;
this.value = value;
this.text = text;
};

(function (bindDropdownAndSetValue) {
function bindDropDownValue(response, dropdownObject) {
$.each(response, function (i, e) {
$('#' + dropdownObject.id).append('<option value=' + e[dropdownObject.value] + '>' + e[dropdownObject.text] + '</option>');
});
}
function dropdownValues(id, value, text) {
this.id = id;
this.value = value;
this.text = text;
}
Object.assign(bindDropdownAndSetValue, {bindDropDownValue, dropdownValues });
} (bindDropdownAndSetValue));

Related

Drop last query in client side

I have a dropdown who populate depending of selected radio button:
JS
$(function getJsonProveedores() {
var items = "";
$('input[type=radio][name=editList]').change(function () {
if (this.value == 'Proveedor') {
$.getJSON("#Url.Action("GetProveedores", "Agenda")", function (data) {
$.each(data, function (index, item) {
items += "<option value='" + item.ID + "'>" + item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
});
}
else if (this.value == 'Sucursal') {
$.getJSON("#Url.Action("GetUnidades", "Agenda")", function (data) {
$.each(data, function (index, item) {
items += "<option value='" + item.ID + "'>" + item.Nombre + "</option>";
});
$("#lstProveedor").html(items);
});
} else if (this.value == 'Usuario') {
$.getJSON("#Url.Action("GetUsuario", "Agenda")", function (data) {
$.each(data, function (index, item) {
items += "<option value='" + item.ID + "'>" + item.Nombre + "</option>";
});
$("#lstProveedor").html(items);
});
}
});
});
It load correctly all JSON, but I have an issue removing last query, for example if i click Proveedor radio, it load:
$.getJSON("#Url.Action("GetProveedores", "Agenda")"
and next if I click Sucursal radio, it load
$.getJSON("#Url.Action("GetUnidades", "Agenda")"
The problem is I keep seeing first query result of
$.getJSON("#Url.Action("GetProveedores", "Agenda")"
instead getting only second one:
$.getJSON("#Url.Action("GetUnidades", "Agenda")"
Controller:
public ActionResult GetProveedores()
{
var listaProveedores = db.Proveedores.ToList();
return Json(listaProveedores, JsonRequestBehavior.AllowGet);
}
public ActionResult GetUnidades()
{
var listaUnidades = db.Unidades.ToList();
return Json(listaUnidades, JsonRequestBehavior.AllowGet);
}
public ActionResult GetUsuario()
{
var listaUsuarios = db.Usuarios.ToList();
return Json(listaUsuarios, JsonRequestBehavior.AllowGet);
}
What can be the problem there? Regards
The way the functions/variables are structured, items never falls out of scope. So it never gets reset. Each subsequent AJAX call is simply appending to it.
Instead, get rid of the items variable from its current scope and use one local to each scope where you need it:
$(function getJsonProveedores() {
$('input[type=radio][name=editList]').change(function () {
if (this.value == 'Proveedor') {
$.getJSON("#Url.Action("GetProveedores", "Agenda")", function (data) {
var items = ""; // <--- declare it here
$.each(data, function (index, item) {
items += "<option value='" + item.ID + "'>" + item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
});
}
else if (this.value == 'Sucursal') {
// ... and so on, declaring an "items" in each scope where you need it

JQuery Dynamic Objects load selectors

I've a form when I click one radio button to load a subform.
Ok this work perfectly, but has 3 selectors that I need external data when only this subform loaded.
So, I did in this way:
$(document).on('focus', '#reemb', function () {
$.getJSON("/banks.php", function (json) {
$('#bank').empty();
$.each(json, function (i, obj) {
$('#bank').append($('<option>').text(obj.name).attr('value', obj.code));
});
});
$.getJSON('/statecity.json', function (data) {
var items = [];
var options = '<option value="">State</option>';
$.each(data, function (key, val) {
options += '<option value="' + val.name + '">' + val.name + '</option>';
});
$("#state").html(options);
$("#state").change(function () {
var options_city = '';
var str = "";
$("#state option:selected").each(function () {
str += $(this).text();
});
$.each(data, function (key, val) {
if (val.name == str) {
$.each(val.city, function (key_city, val_city) {
options_city += '<option value="' + val_city + '">' + val_city + '</option>';
});
}
});
$("#city ").html(options_city);
}).change();
});
});
This work fine, but everytime that I need to change one date the selectors clear and load again.
I tried to add tag onload to start the function to load selectors in this subform, but don't works. Also tried change events to .on, but also don't work.
How I need to do this?
Thx!!
Not knowing what #reemb is, I would empty the relevant sub selects:
If the container holding the selects is ALSO emptied, you need to delegate all even handlers of objects inside too - like $(document).on("change","#bank", function() {
$(document).on('click', '#reemb', function() {
$.getJSON("/banks.php", function(json) {
$('#bank').empty();
$.each(json, function(i, obj) {
$('#bank').append($('<option>').text(obj.name).attr('value', obj.code)).change();
});
});
$('#bank').on("change", function() {
$('#city').empty();
$.getJSON('/statecity.json', function(data) {
var items = [];
var options = '<option value="">State</option>';
$.each(data, function(key, val) {
options += '<option value="' + val.name + '">' + val.name + '</option>';
});
$("#state").html(options).change(); // if needed
});
$("#state").on("change", function() {
var options_city = '';
var str = "";
$("#state option:selected").each(function() {
str += $(this).text();
});
$.each(data, function(key, val) {
if (val.name == str) {
$.each(val.city, function(key_city, val_city) {
options_city += '<option value="' + val_city + '">' + val_city + '</option>';
});
}
});
$("#city ").html(options_city).change(); // if needed
});
});
});

how get data json with parameter

i have url : http://cgncrdev.gandsoft.com/ws/get.php?fcid=gen_ncr_id&origin_id=OR10&suborigin_id=OR13
anyway, you can open it url..
i try this but not working
function gen_ncr_id() {
$.getJSON(baseUrl + '/ws/get.php?fcid=gen_ncr_id&origin_id=OR10&suborigin_id=OR13', function(data) {
$.each(data.items, function(key, val) {
alert(val.gen_ncr_id)
opt = '<input type="text" value="' + val.gen_ncr_id + '">'
$(opt).appendTo('#id_ncr')
})
})
}
output : undefined
can help me ?
try this:
var data = {"items":[{"gen_ncr_id('OR10','OR13')":"4.13\/4.10.4\/16\/002"}]};
function getPrefixValue(obj, prefix) {
var result;
var re = new RegExp('^' + prefix);
$.each(obj, function(key, value) {
if (key.match(re)) {
result = value;
return false; // break the each loop
}
});
return result;
}
$.each(data.items, function(key, val) {
var value = getPrefixValue(val, 'gen_ncr_id');
alert(value);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

AngularJS: Factory and filters - factory is not working

I have this code, and it works:
var app = angular.module('twitterApp', ['twitterApp.services', 'ngSanitize']);
app.filter('clearImage', function () {
return function (text) {
var str = text.replace(/_normal./g, '.');
return str;
};
});
app.filter('links', function () {
return function (text) {
var str = text.replace(/#([^ ']+)/g, function(u, screen_name) {
var link = '<a target=blank href="http://twitter.com/intent/user?screen_name=' + screen_name + '">' + u + '</a>';
return link;
});
str = str.replace(/#([^ ']+)/g, function (t, hash) {
var link = '<a target=blank href="https://twitter.com/hashtag/' + hash + '?src=hash">' + t + '</a> ';
return link;
});
return str;
};
});
I am trying to be more object oriented and modular, so I have made the following code, but it is not working:
var app = angular.module('twitterApp', ['twitterApp.services', 'ngSanitize']);
app.factory('StratoFactory', function() {
var factory = {};
return {
removeNormalStringFromImage : function(text) {
var str = text.replace(/_normal./g, '.');
return str;
},
userName2Link : function(text) {
var str = text.replace(/#([^ ']+)/g, function(u, screen_name) {
var link = '<a target=blank href="http://twitter.com/intent/user?screen_name=' + screen_name + '">' + u + '</a>';
return link;
});
str = str.replace(/#([^ ']+)/g, function (t, hash) {
var link = '<a target=blank href="https://twitter.com/hashtag/' + hash + '?src=hash">' + t + '</a> ';
return link;
});
return str;
}
};
return factory;
});
app.filter('clearImage', function(StratoFactory) {
return function(text) {
StratoFactory.removeNormalStringFromImage(text);
};
});
app.filter('links', function(StratoFactory) {
return function(text) {
StratoFactory.userName2Link(text);
};
});
Can someone explain me the reason what is wrong with the second version of the code? Thanks!
You have two return statements in your factory.
you need to create an object, assign method to it, then return it.
try this:
app.factory('StratoFactory', function() {
var factory = {};
factory.removeNormalStringFromImage = function(text) {
var str = text.replace(/_normal./g, '.');
return str;
}
factory.userName2Link = function(text) {
var str = text.replace(/#([^ ']+)/g, function(u, screen_name) {
var link = '<a target=blank href="http://twitter.com/intent/user?screen_name=' + screen_name + '">' + u + '</a>';
return link;
});
str = str.replace(/#([^ ']+)/g, function (t, hash) {
var link = '<a target=blank href="https://twitter.com/hashtag/' + hash + '?src=hash">' + t + '</a> ';
return link;
});
return str;
}
return factory;
});
I have finally found the solution! There wasn't any error in the console, because everything was structured ok. But the problem was that my filters weren't returning anything. So I have simply added a return, and now everything is ok. Really a banal mistake. Here is the code:
var app = angular.module('twitterApp', ['twitterApp.services', 'ngSanitize']);
app.factory('StratoFactory', function() {
var factory = {};
factory.removeNormalStringFromImage = function(text) {
var str = text.replace(/_normal./g, '.');
return str;
},
factory.userName2Link = function(text) {
var str = text.replace(/#([^ ']+)/g, function(u, screen_name) {
var link = '<a target=blank href="http://twitter.com/intent/user?screen_name=' + screen_name + '">' + u + '</a>';
return link;
});
str = str.replace(/#([^ ']+)/g, function (t, hash) {
var link = '<a target=blank href="https://twitter.com/hashtag/' + hash + '?src=hash">' + t + '</a> ';
return link;
});
return str;
};
return factory;
});
app.filter('clearImage', function(StratoFactory) {
return function(text) {
**return** StratoFactory.removeNormalStringFromImage(text);
};
});
app.filter('links', function(StratoFactory) {
return function(text) {
**return** StratoFactory.userName2Link(text);
};
});

getJSON not satisfied

I have 3 selects:
country, region, city
When choosing a country to be updated select the region on the country.
here's the code. like written logically. but the region is not updated
$(document).ready(function() {
$('select[name=ad_country]').change(function() {
current_country = $(this).val();
$.getJSON('./core/AJAX/advertisement_changecountry.php', {country: current_country},
function(data) {
$('select[name=ad_region]').empty();
$.each(data.region, function(key, val) {
$('select[name=ad_region]').append('<option value="'+val.id_parent+'">'+val.name+'</option>');
});
$('select[name=ad_city]').empty();
$.each(data.city, function(key, val) {
$('select[name=ad_city]').append('<option value="'+val.id_parent+'">'+val.name+'</option>');
});
});
}
);
}
you have an error on your clossing tags
You have missed the '}' at the end.Now try this Code :
$(document).ready(function () {
$('select[name=ad_country]').change(function () {
current_country = $(this).val();
$.getJSON('./core/AJAX/advertisement_changecountry.php', { country: current_country },
function (data) {
$('select[name=ad_region]').empty();
$.each(data.region, function (key, val) {
$('select[name=ad_region]').append('<option value="' + val.id_parent + '">' + val.name + '</option>');
});
$('select[name=ad_city]').empty();
$.each(data.city, function (key, val) {
$('select[name=ad_city]').append('<option value="' + val.id_parent + '">' + val.name + '</option>');
});
});
});
});

Categories