I have a page which uses dropdowns to filter a listing. I have over 10 filters now and each of the change function, I am calling an AJAX request and passing corresponding variables to the PHP function. Like this :
$("#categories").change(function() {
uri = "myurl" ;
var status=$("#statusfilter").val();
var category=$("#categories").val();
var network=$("#networksfilter").val();
var prod_type = $("#prodtypefilter").val();
loadData(uri,category,status,network,prod_type);
});
and in loadData() I have the following code :
function loadData(uri,category,status,network,prod_type){
url + = category+"/"+status+"/"+network+"/"+prod_type;
$('#userdata').load(url);
}
Here I have given only 4 filters only, but it is actually 10 and may increase.Anyway this is working fine. But the problem is that as I increase the filters, I need to write this same for every dropdown change function. Is there any better approach to optimze the code and so I don't need to load a bunch of JS ?
Rename your filter elements' IDs to start with same word, for example "filter_". Then get all of them at once:
$('select[id^="filter_"]').change(function() {
var uri = "myurl";
var filters = new Array();
$('select[id^="filter_"]').map(function () {
filters[$(this).name()] = $(this).val(); // not tested, just an idea
});
loadData(uri,filters);
});
.map() iterates over its elements, invoking a function on each of them and recording the selected option value in the array.
You can use .each() if it's more intuitive from .map() for you:
$.each('select[id^="filter_"]', function() {
filters[$(this).name()] = $(this).val(); // not tested, just an idea
});
Note: It's a good idea to use associative array as #Tony noticed below to be sure which filter is for which database table attribute in your server side script.
You will need to write some code in any cases, but you can reduce it, for example like this:
$("#categories").change(function() {
uri = "myurl";
var filters = {
status: $("#statusfilter").val(),
category: $("#categories").val(),
network: $("#networksfilter").val(),
prod_type: $("#prodtypefilter").val()
}; // order is important
loadData(filters );
});
loadData(filters) {
var url = '';
for (var filterName in filters)
url += '/' + (filters[filterName] || 'any'); // here some def value needed
url = url.substring(1); // cut first slash
$('#userdata').load(url);
}
EDIT
Or even like this:
loadData(filters) {
var url = Object.keys(filters).map(function(el) {
return filters[el] || 'any';
}).join('/');
$('#userdata').load(url);
}
Related
I can print out all the ng-show values, but I can't filter out what I want.
I don't know if it's a regular expression error or an angularjs. I tried it directly in the developer tools and the result is successful.
Please check the full code in codepen, thanks
var thList = $('thead').find('th');
var fieldPattern = /\'(.*)\'.*\|.*/g;
var allTableField = [];
var valueList = [];
angular.forEach(thList, function(th) {
var value = $(th).attr('ng-show');
console.log(value);
if (/showField/g.test(value)) {
valueList.push(value);
var results = fieldPattern.exec(value);
if (results) {
allTableField.push(results[1]);
}
}
});
Codepen
Sorry, my English is terrible and difficult to express.
I want to get ng-show values through JQ and filter out values that match regular expressions.
In the end, I only got part of it.
enter image description here
So your valueList contains more 'values' than your allTabField, the rest of the values are filtered by your regex fieldPattern
EDIT:
Use RegExp constructor like var fieldPattern = new RegExp("\'(.*)\'.*\|.*");
Alternative Solution:
angular.forEach(thList, function(th) {
var value = $(th).attr('ng-show');
console.log(value);
if (/showField/g.test(value)) {
valueList.push(value);
/* changes are made here */
var index = value.indexOf('|');
var results = value.substring(1, index - 1);
if (results) {
allTableField.push(results);
}
/* End of changes */
}
});
I have build an dynamic ajax function that saves data-xxx-values of elements to process the data. However I want to shorten this code which takes values depending on the ajax-request I want to process:
var data_form = $(element).attr('data-form');
var data_index = $(element).attr('data-index');
var data_hide_error = $(element).data('hide-error');
var data_disable_blur = $(element).data('disable-blur');
var data_hide_success = $(element).data('hide-success');
in a way that I only have one or two lines of code where I check which data-values are given in the element and if there is one data-value, I want to create a variable with that exact name.
For example: I click on this anchor send and my function would create the variables var data_index = 1; and var data_form = '#registerForm'; automatically.
How could I achieve this?
Perhaps you meant this: Using .data() will return all data-attributes in one object to use in the function that you call
$(function() {
$("a").on("click",function(e) {
e.preventDefault();
console.log($(this).data())
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
send
I want to replace a dynamic url query parameter with another parameter.
Eg. like my url is:
http://www.mysite.com/209-0539.prd?pageLevel=&skuId=111-4567&sc_cmp=pcp_GSF_Batteries+%26+Electrical+Accessories_209-0539
I want to replace everything starting after
&sc_cmp=pcp_GSF_Batteries+%26+Electrical+Accessories_209-0539
and add something like & new Static string
My final url should look like:
http://www.mysite.com/209-0539.prd?pageLevel=&skuId=111-4567& new static string.
Thanks
I recommend you to use the cool URI.js library, then it's as easy as:
var url = "http://www.mysite.com/209-0539.prd?pageLevel=&skuId=111-4567&sc_cmp=pcp_GSF_Batteries+%26+Electrical+Accessories_209-0539";
url = URI(url).removeSearch("sc_cmp").addSearch("newvar","newval");
// http://www.mysite.com/209-0539.prd?pageLevel=&skuId=111-4567&newvar=newval
alert(url);
See working demo .
If you don't want to include another library, following lets you add as many search items you want removed and add as many as you like without a lot of code
/* array of search keys to remove*/
var removeSearch = ['sc_cmp'];
/* array of new search items*/
var newSearchitem = ['image=cool'];
var url = location.href;
var pageUrl = url.split('?')[0];
var urlSearch = url.split('?')[1].split('&');
/* store search items in array */
var newSearchArr = [];
/* loop over exisiting search items and store keepers*/
for (i = 0; i < urlSearch.length; i++) {
var key = urlSearch[i].split('=')[0];
if ($.inArray(key, removeSearch) == -1) {
newSearchArr.push(urlSearch[i])
}
}
$.merge(newSearchArr, newSearchitem);
var newUrl = pageUrl + '?' + newSearchArr.join('&')
DEMO: http://jsfiddle.net/9VPUX/
I'm trying to extract a URL from an array using JS but my code doesn't seem to be returning anything.
Would appreciate any help!
var pages = [
"www.facebook.com|Facebook",
"www.twitter.com|Twitter",
"www.google.co.uk|Google"
];
function url1_m1(pages, pattern) {
var URL = '' // variable ready to accept URL
for (var i = 0; i < pages[i].length; i++) {
// for each character in the chosen page
if (pages[i].substr(i, 4) == "www.") {
// check to see if a URL is there
while (pages[i].substr(i, 1) != "|") {
// if so then lets assemble the URL up to the colon
URL = URL + pages[i].substr(i, 1);
i++;
}
}
}
return (URL);
// let the user know the result
}
alert(url1_m1(pages, "twitter")); // should return www.twitter.com
In your case you can use this:
var page = "www.facebook.com|Facebook";
alert(page.match(/^[^|]+/)[0]);
You can see this here
It's just example of usage RegExp above. Full your code is:
var pages = [
"www.facebook.com|Facebook",
"www.twitter.com|Twitter",
"www.google.co.uk|Google"
];
var parseUrl = function(url){
return url.match(/^(www\.[^|]+)+/)[0];
};
var getUrl = function(param){
param = param.toLowerCase();
var page = _(pages).detect(function(page){
return page.toLowerCase().search(param)+1 !== 0;
});
return parseUrl(page);
};
alert(getUrl('twitter'));
You can test it here
In my code I have used Underscore library. You can replace it by standard for or while loops for find some array item.
And of course improve my code by some validations - for example, for undefined value, or if values in array are incorrect or something else.
Good luck!
Im not sure exactly what you are trying to do, but you could use split() function
var pair = pages[i].split("|");
var url = pair[0], title=pair[1];
Users will be hitting up against a URL that contains a query string called inquirytype. For a number of reasons, I need to read in this query string with javascript (Dojo) and save its value to a variable. I've done a fair amount of research trying to find how to do this, and I've discovered a few possibilities, but none of them seem to actually read in a query string that isn't hard-coded somewhere in the script.
You can access parameters from the url using location.search without Dojo Can a javascript attribute value be determined by a manual url parameter?
function getUrlParams() {
var paramMap = {};
if (location.search.length == 0) {
return paramMap;
}
var parts = location.search.substring(1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
Then you could do the following to extract id from the url /hello.php?id=5&name=value
var params = getUrlParams();
var id = params['id']; // or params.id
Dojo provides http://dojotoolkit.org/reference-guide/dojo/queryToObject.html which is a bit smarter than my simple implementation and creates arrays out of duplicated keys.
var uri = "http://some.server.org/somecontext/?foo=bar&foo=bar2&bit=byte";
var query = uri.substring(uri.indexOf("?") + 1, uri.length);
var queryObject = dojo.queryToObject(query);
//The structure of queryObject will be:
// {
// foo: ["bar", "bar2],
// bit: "byte"
// }
In new dojo it's accessed with io-query:
require([
"dojo/io-query",
], function (ioQuery) {
GET = ioQuery.queryToObject(decodeURIComponent(dojo.doc.location.search.slice(1)));
console.log(GET.id);
});
Since dojo 0.9, there is a better option, queryToObject.
dojo.queryToObject(query)
See this similar question with what I think is a cleaner answer.