Use dropdown selection in URL - javascript

I'm following the answer here to use the selection from a dropdown in a URL. I am using asp.net core, using:
asp-page="/Page" asp-page-handler="Action"
To do the redirect
The script below (from the link above) works great, except if you select an item from the dropdown then select a different one (and on and on), it appends both to the URL.
<script>
$("[name=selectedAnalyst]").on("change", function () {
var analystId = $(this).val();
var accept = $(this).closest('td').next().find("a")[0];
var oldUrl = accept.href;
var newUrl = oldUrl + "&analystid=" + analystId;
$(accept).attr("href", newUrl);
})
I tried scrubbing the parameter in question (using params.delete) but it's not working:
<script>
$("[name=selectedAnalyst]").on("change", function () {
var analystId = $(this).val();
var accept = $(this).closest('td').next().find("a")[0];
var oldUrl = accept.href;
let params = new URLSearchParams(oldUrl.search);
params.delete('analystid')
var newUrl = oldUrl + "&analystid=" + analystId;
$(accept).attr("href", newUrl);
})
Is there a way to get the above script to work how I envision, or a better way to do this?
Thank you

it seems that
let params = new URLSearchParams(oldUrl.search);
params.delete('analystid')
does not work
I tried with the codes and it could work
<script>
$("[name=selectedAnalyst]").on("change", function () {
var analystId = $(this).val();
var accept = $(this).closest('td').next().find("a")[0];
var oldUrl = accept.href;
var a = oldUrl.indexOf("analystid");
console.log(a);
if (a == -1)
{
var newUrl = oldUrl + "&analystid=" + analystId;
}
else
{
var newUrl= oldUrl.substring(0, oldUrl.length - 1) + analystId;
}
console.log(newUrl);
console.log(oldUrl);
$(accept).attr("href", newUrl);
})
</script>

Building on what Ruikai Feng posted I think this is working:
$("[name=selectedAnalyst]").on("change", function () {
var analystId = $(this).val();
var accept = $(this).closest('td').next().find("a")[0];
var oldUrl = accept.href;
var a = oldUrl.indexOf("analystId ");
if (a == -1) {
var newUrl = oldUrl + "&analystId =" + analystId ;
}
else {
var newUrl = oldUrl.substring(0, a - 1) + "&analystId =" + analystId;
}
$(accept).attr("href", newUrl);
})

Related

How do I add a part of a Url as as first search param?

This is my setup
<script>
$(document).ready(function() {
document.querySelectorAll(".money").forEach(function(e) {
e.addEventListener("click", function() {
setTimeout(function() {
myfunction();
}, 300);
});
});
});
function myfunction() {
var urlParams = window.location.search;
var typ = "produkttyp=Tasting";
var urlParamsUpdate = typ.slice(0,-3)+ urlParams + typ.slice(-1);
var newUrl = "/collections/alle/" + urlParamsUpdate;
window.location.href = newUrl.slice(0, -2) + "0%2C" + newUrl.slice(-2);
}
</script>
The result is the following url:
produkttyp=Tast?kategorie=Rotwein&money=10%2C0g
But thats not the result i am looking for. The wanted result is:
?produkttyp=Tasting&kategorie=Rotwein&money=0%2C25
So bascially I just want the ?produkttyp=Tasting& as the first search parameter, but its not working out. The mistake is somewhere here. I cant slice it the right way.
var urlParamsUpdate = typ.slice(0,-3)+ urlParams + typ.slice(-1);
Can somebody help me out?
I found a workaround:
<script>
$(document).ready(function() {
document.querySelectorAll(".money").forEach(function(e) {
e.addEventListener("click", function() {
setTimeout(function() {
myfunction();
}, 300);
});
});
});
function myfunction() {
var urlParams = window.location.search;
const urlParamsUpdate = urlParams.slice(1);
const urlUpdateMoney = urlParamsUpdate.slice(0, -2) + "0%2C" + urlParamsUpdate.slice(-2);
const url = "?produkttyp=tasting&";
window.location.href = "/pages/..." + url + urlUpdateMoney ;
}
</script>
Now I am just slicing away the "?" from the urlParams and then insert the missing part of the url "?produkttyp=tasting&" in the first place.

How to add or replace a query parameter in a URL using Javascript/jQuery?

I'm using jQuery 1.12. I want to replace a query string parameter in my window's URL query string, or add the parameter if doesn't exist. I tried the below:
new_url = window.location.href.replace( /[\?#].*|$/, "?order_by=" + data_val )
window.location.href = new_url
but what I'm discovering is that this wipes out all previous parameters in the query string, which I don't want. If the query string is:
?a=1&b=2
I would want the new query string to be:
?a=2&b=2&order_by=data
and if the query string was:
?a=2&b=3&order_by=old_data
it would become:
?a=2&b=3&order_by=data
You could use a jQuery plugin to do the all the heavy lifting for you. It will parse the query string, and also reconstruct the updated query string for you. Much less code to deal with.
Plugin Download Page
Github Repo
// URL: ?a=2&b=3&order_by=old_data
var order_by = $.query.get('order_by');
//=> old_data
// Conditionally modify parameter value
if (order_by) {
order_by = “data”;
}
// Inject modified parameter back into query string
var newUrl = $.query.set(“order_by”, order_by).toString();
//=> ?a=2&b=3&order_by=data
For those using Node.js, there is a package for this available in NPM.
NPM Package
Github Repo
var queryString = require('query-string');
var parsed = queryString.parse('?a=2&b=3&order_by=old_data'); // location.search
// Conditionally modify parameter value
if (parsed.order_by) {
parsed.order_by = 'data';
}
// Inject modified parameter back into query string
const newQueryString = queryString.stringify(parsed);
//=> a=2&b=3&order_by=data
A good solution ought to handle all of the following:
A URL that already has an order_by query parameter, optionally with whitespace before the equals sign. This can be further divided into cases where the order_by appears at the start, middle or end of the query string.
A URL that doesn't already have and order_by query parameter but does already have a question mark to delimit the query string.
A URL that doesn't already have and order_by query parameter and doesn't already have a question mark to delimit the query string.
The following will handle the cases above:
if (/[?&]order_by\s*=/.test(oldUrl)) {
newUrl = oldUrl.replace(/(?:([?&])order_by\s*=[^?&]*)/, "$1order_by=" + data_val);
} else if (/\?/.test(oldUrl)) {
newUrl = oldUrl + "&order_by=" + data_val;
} else {
newUrl = oldUrl + "?order_by=" + data_val;
}
as demonstrated below:
getNewUrl("?a=1&b=2");
getNewUrl("?a=2&b=3&order_by=old_data");
getNewUrl("?a=2&b=3&order_by = old_data&c=4");
getNewUrl("?order_by=old_data&a=2&b=3");
getNewUrl("http://www.stackoverflow.com");
function getNewUrl(oldUrl) {
var data_val = "new_data";
var newUrl;
if (/[?&]order_by\s*=/.test(oldUrl)) {
newUrl = oldUrl.replace(/(?:([?&])order_by\s*=[^?&]*)/, "$1order_by=" + data_val);
} else if (/\?/.test(oldUrl)) {
newUrl = oldUrl + "&order_by=" + data_val;
} else {
newUrl = oldUrl + "?order_by=" + data_val;
}
console.log(oldUrl + "\n...becomes...\n" + newUrl);
}
something like this?
let new_url = "";
if (window.location.search && window.location.search.indexOf('order_by=') != -1) {
new_url = window.location.search.replace( /order_by=\w*\d*/, "order_by=" + data_val);
} else if (window.location.search) {
new_url = window.location.search + "&order_by=" + data_val;
} else {
new_url = window.location.search + "?order_by=" + data_val;
}
window.location.href = new_url;
function addOrReplaceOrderBy(newData) {
var stringToAdd = "order_by=" + newData;
if (window.location.search == "")
return window.location.href + stringToAdd;
if (window.location.search.indexOf('order_by=') == -1)
return window.location.href + stringToAdd;
var newSearchString = "";
var searchParams = window.location.search.substring(1).split("&");
for (var i = 0; i < searchParams.length; i++) {
if (searchParams[i].indexOf('order_by=') > -1) {
searchParams[i] = "order_by=" + newData;
break;
}
}
return window.location.href.split("?")[0] + "?" + searchParams.join("&");
}
window.location.href = addOrReplaceOrderBy("new_order_by");
A little long but I think it works as intended.
You can remove parameter from query string using URLSearchParams https://developer.mozilla.org/ru/docs/Web/API/URLSearchParams?param11=val
It is not yet supported by IE and Safari, but you can use it by adding polyfill https://github.com/jerrybendy/url-search-params-polyfill
And for accessing or modifying query part of the URI you should use "search" property of the window.location.
Working code example:
var a = document.createElement("a")
a.href = "http://localhost.com?param1=val&param2=val2&param3=val3#myHashCode";
var queryParams = new URLSearchParams(a.search)
queryParams.delete("param2")
a.search = queryParams.toString();
console.log(a.href);
Try this:
For reading parameters:
const data = ['example.com?var1=value1&var2=value2&var3=value3', 'example.com?a=2&b=2&order_by=data']
const getParameters = url => {
const parameters = url.split('?')[1],
regex = /(\w+)=(\w+)/g,
obj = {}
let temp
while (temp = regex.exec(parameters)){
obj[temp[1]] = decodeURIComponent(temp[2])
}
return obj
}
for(let url of data){
console.log(getParameters(url))
}
For placing only this parameters:
const data = ['example.com?zzz=asd']
const parameters = {a:1, b:2, add: "abs"}
const setParameters = (url, parameters) => {
const keys = Object.keys(parameters)
let temp = url.split('?')[0] += '?'
for (let i = 0; i < keys.length; i++) {
temp += `${keys[i]}=${parameters[keys[i]]}${i == keys.length - 1 ? '' : '&'}`
}
return temp
}
for (let url of data){
console.log(setParameters(url, parameters))
}
And finaly for inserting (or replace while exists)
const data = ['example.com?a=123&b=3&sum=126']
const parameters = {order_by: 'abc', a: 11}
const insertParameters = (url, parameters) => {
const keys = Object.keys(parameters)
let result = url
for (let i = 0; i < keys.length; i++){
if (result.indexOf(keys[i]) === -1) {
result += `&${keys[i]}=${encodeURIComponent(parameters[keys[i]])}`
} else {
let regex = new RegExp(`${keys[i]}=(\\w+)`)
result = result.replace(regex, `&${keys[i]}=${encodeURIComponent(parameters[keys[i]])}`)
}
}
return result
}
for (let url of data){
console.log(insertParameters(url, parameters))
}
Hope this works for you ;)
After using function just replace window.location.href
This small function could help.
function changeSearchQueryParameter(oldParameter,newParameter,newValue) {
var parameters = location.search.replace("?", "").split("&").filter(function(el){ return el !== "" });
var out = "";
var count = 0;
if(oldParameter.length>0) {
if(newParameter.length>0 && (newValue.length>0 || newValue>=0)){
out += "?";
var params = [];
parameters.forEach(function(v){
var vA = v.split("=");
if(vA[0]==oldParameter) {
vA[0]=newParameter;
if((newValue.length>0 || newValue>=0)) {
vA[1] = newValue;
}
} else {
count++;
}
params.push(vA.join("="));
});
if(count==parameters.length) {
params.push([newParameter,newValue].join("="));
}
params = params.filter(function(el){ return el !== "" });
if(params.length>1) {
out += params.join("&");
}
if(params.length==1) {
out += params[0];
}
}
} else {
if((newParameter.length>0) && (newValue.length>0 || newValue>=0)){
if(location.href.indexOf("?")!==-1) {
var out = "&"+newParameter+"="+newValue;
} else {
var out = "?"+newParameter+"="+newValue;
}
}
}
return location.href+out;
}
// if old query parameter is declared but does not exist in url then new parameter and value is simply added if it exists it will be replaced
console.log(changeSearchQueryParameter("ib","idx",5));
// add new parameter and value in url
console.log(changeSearchQueryParameter("","idy",5));
// if no new or old parameter are present url does not change
console.log(changeSearchQueryParameter("","",5));
console.log(changeSearchQueryParameter("","",""));
Maybe you could try tweaking the regular expression to retrieve only the values you're looking for, then add or update them in a helper function, something like this:
function paramUpdate(param) {
var url = window.location.href,
regExp = new RegExp(param.key + '=([a-z0-9\-\_]+)(?:&)?'),
existsMatch = url.match(regExp);
if (!existsMatch) {
return url + '&' + param.key + '=' + param.value
}
var paramToUpdate = existsMatch[0],
valueToReplace = existsMatch[1],
updatedParam = paramToUpdate.replace(valueToReplace, param.value);
return url.replace(paramToUpdate, updatedParam);
}
var new_url = paramUpdate({
key: 'order_by',
value: 'id'
});
window.location.href = new_url;
Hope it works well for your needs!
To use Regex pattern, I prefer this one:
var oldUrl = "http://stackoverflow.com/";
var data_val = "newORDER" ;
var r = /^(.+order_by=).+?(&|$)(.*)$/i ;
var newUrl = "";
var matches = oldUrl.match(r) ;
if(matches===null){
newUrl = oldUrl + ((oldUrl.indexOf("?")>-1)?"&":"?") + "order_by=" + data_val ;
}else{
newUrl = matches[1]+data_val+matches[2]+matches[3] ;
}
conole.log(newUrl);
If no order_by exist, matches is null and order_by=.. should come after ? or & (if other parameters exist, new one needs &).
If order_by exist, matches has 3 items, see here
Based on AVAVT´s answer I improved it so it takes any key, and I also fixed the missing "?" if there was no querystring
function addOrReplace(key, value) {
var stringToAdd = key+"=" + value;
if (window.location.search == "")
return window.location.href + '?'+stringToAdd;
if (window.location.search.indexOf(key+'=') == -1)
return window.location.href + stringToAdd;
var newSearchString = "";
var searchParams = window.location.search.substring(1).split("&");
for (var i = 0; i < searchParams.length; i++) {
if (searchParams[i].indexOf(key+'=') > -1) {
searchParams[i] = key+"=" + value;
break;
}
}
return window.location.href.split("?")[0] + "?" + searchParams.join("&");
}
usuage:
window.location.href = addOrReplace('order_by', 'date_created');
if you would not want to reload the page you can use pushState Api
if (history.pushState) {
var newurl = addOrReplace('order_by', 'date_created');
window.history.pushState({path:newurl},'',newurl);
}
function myFunction() {
var str = "https://www.citicards.com/cards/credit/application/flow.action?app=UNSOL&HKOP=828cca70910b4fe25e118bd0b59b89c3c7c560df877909495d8252d20026cf8d&cmp=afa|acquire|2003|comparecards&ranMID=44660&ranEAID=2759285&ProspectID=516511657A844EF3A6F0C2B1E85FEFB0&ID=3000";
var res = str.split("&");
var myKey;
if (!str.includes("ranSiteID")) {
console.log("key not found ");
res.push('ranSiteID=samplearsdyfguh.090-nuvbknlmc0.gvyhbjknl')
console.log(res.join("&"));
} else {
res.map(function(key) {
console.log("my keys", key);
if (key.includes("ranSiteID")) {
console.log("my required-->key", key);
mykey = key.split("=");
console.log(mykey);
}
})
}
document.getElementById("demo").innerHTML = res;
}
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display the array values after the split.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
</body>
</html>

Get the hash value which was before hashchange

Suppose my html is
One
Two
and Js is
$(window).on("hashchange"){
alert(document.location.hash);
}
I want to get the hash value which was before hash change .Is it Possible?If yes ,How?
use that
$(window).on("hashchange", function(e){
console.log(e.originalEvent.oldURL)
console.log(e.originalEvent.newURL)
})​;
Demo: http://jsbin.com/ulumil/
You have to track the last hash, for example:
var currentHash = function() {
return location.hash.replace(/^#/, '')
}
var last_hash
var hash = currentHash()
$(window).bind('hashchange', function(event){
last_hash = hash
hash = currentHash()
console.log('hash changed from ' + last_hash + ' to ' + hash)
});
Actually the solution provided by Amit works but with jquery library and crossplatform as well.
Here is a more simplified solution using core javascript and crossbrowser as well. (checked with latest version of IE/FF/Chrome/Safari)
window.onhashchange = function(e){
console.log(e);
var oldURL = e.oldURL;
var newURL = e.newURL;
console.log("old url = " + oldURL);
console.log("new url = " + newURL);
var oldHash = oldURL.split("#")[1];
var newHash = newURL.split("#")[1];
console.log(oldHash);
console.log(newHash);
};
Don't use
$(window).on("hashchange", function(e){
console.log(e.originalEvent.oldURL)
console.log(e.originalEvent.newURL)
})​;
It won't work on IE and probably elsewhere too.
Use this rather.
(function(w, $){
var UrlHashMonitor = {};
UrlHashMonitor.oldHash = '';
UrlHashMonitor.newHash = '';
UrlHashMonitor.oldHref = '';
UrlHashMonitor.newHref = '';
UrlHashMonitor.onHashChange = function(f){
$(window).on('hashchange', function(e){
UrlHashMonitor.oldHash = UrlHashMonitor.newHash;
UrlHashMonitor.newHash = w.location.hash;
UrlHashMonitor.oldHref = UrlHashMonitor.newHref;
UrlHashMonitor.newHref = w.location.href;
f(e);
});
};
UrlHashMonitor.init = function(){
UrlHashMonitor.oldHash = UrlHashMonitor.newHash = w.location.hash;
UrlHashMonitor.oldHref = UrlHashMonitor.newHref = w.location.href;
};
w.UrlHashMonitor = UrlHashMonitor;
return UrlHashMonitor;
})(window, window.jQuery);
/*
* USAGE EXAMPLE
*/
UrlHashMonitor.init();
UrlHashMonitor.onHashChange(function(){
console.log('oldHash: ' + UrlHashMonitor.oldHash);
console.log('newHash: ' + UrlHashMonitor.newHash);
console.log('oldHref: ' + UrlHashMonitor.oldHref);
console.log('newHref: ' + UrlHashMonitor.newHref);
//do other stuff
});
This should work in all modern browsers.
DEMO: https://output.jsbin.com/qafupu#one

Updating existing URL querystring values with jQuery

Let's say I have a url such as:
http://www.example.com/hello.png?w=100&h=100&bg=white
What I'd like to do is update the values of the w and h querystring, but leave the bg querystring intact, for example:
http://www.example.com/hello.png?w=200&h=200&bg=white
So what's the fastest most efficient way to read the querystring values (and they could be any set of querystring values, not just w, h, and bg), update a few or none of the values, and return the full url with the new querystring?
So:
Get the values of each querystring key
Update any number of the keys
Rebuild the url with the new values
Keep all of the other values which weren't updated
It will not have a standard set of known keys, it could change per URL
Simple solution
You can use URLSearchParams.set() like below:
var currentUrl = 'http://www.example.com/hello.png?w=100&h=100&bg=white';
var url = new URL(currentUrl);
url.searchParams.set("w", "200"); // setting your param
var newUrl = url.href;
console.log(newUrl);
Online demo (jsfiddle)
Get query string values this way and use $.param to rebuild query string
UPDATE:
This is an example, also check fiddle:
function getQueryVariable(url, variable) {
var query = url.substring(1);
var vars = query.split('&');
for (var i=0; i<vars.length; i++) {
var pair = vars[i].split('=');
if (pair[0] == variable) {
return pair[1];
}
}
return false;
}
var url = 'http://www.example.com/hello.png?w=100&h=100&bg=white';
var w = getQueryVariable(url, 'w');
var h = getQueryVariable(url, 'h');
var bg = getQueryVariable(url, 'bg');
// http://www.example.com/hello.png?w=200&h=200&bg=white
var params = { 'w':200, 'h':200, 'bg':bg };
var new_url = 'http://www.example.com/hello.png?' + jQuery.param(params);
You can change the function to use current url:
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i=0; i<vars.length; i++) {
var pair = vars[i].split('=');
if (pair[0] == variable) {
return pair[1];
}
}
return false;
}
//update URL Parameter
function updateURL(key,val){
var url = window.location.href;
var reExp = new RegExp("[\?|\&]"+key + "=[0-9a-zA-Z\_\+\-\|\.\,\;]*");
if(reExp.test(url)) {
// update
var reExp = new RegExp("[\?&]" + key + "=([^&#]*)");
var delimiter = reExp.exec(url)[0].charAt(0);
url = url.replace(reExp, delimiter + key + "=" + val);
} else {
// add
var newParam = key + "=" + val;
if(!url.indexOf('?')){url += '?';}
if(url.indexOf('#') > -1){
var urlparts = url.split('#');
url = urlparts[0] + "&" + newParam + (urlparts[1] ? "#" +urlparts[1] : '');
} else {
url += "&" + newParam;
}
}
window.history.pushState(null, document.title, url);
}
I like Ali's answer the best. I cleaned up the code into a function and thought I would share it to make someone else's life easier. Hope this helps someone.
function addParam(currentUrl,key,val) {
var url = new URL(currentUrl);
url.searchParams.set(key, val);
return url.href;
}
Another way (independent of jQuery or other libraries): https://github.com/Mikhus/jsurl
var u = new Url;
// or
var u = new Url('/some/path?foo=baz');
alert(u);
u.query.foo = 'bar';
alert(u);
My URL is like this: http://localhost/dentistryindia/admin/hospital/add_procedure?hid=241&hpr_id=12
var reExp = /hpr_id=\\d+/;
var url = window.location.href;
url = url.toString();
var hrpid = $("#category :selected").val(); //new value to replace hpr_id
var reExp = new RegExp("[\\?&]" + 'hpr_id' + "=([^&#]*)"),
delimeter = reExp.exec(url)[0].charAt(0),
newUrl = url.replace(reExp, delimeter + 'hpr_id' + "=" + hrpid);
window.location.href = newUrl;
This is how it worked for me.
Another way you you can do this, using some simple reg ex code by Samuel Santos here like this:
/*
* queryParameters -> handles the query string parameters
* queryString -> the query string without the fist '?' character
* re -> the regular expression
* m -> holds the string matching the regular expression
*/
var queryParameters = {}, queryString = location.search.substring(1),
re = /([^&=]+)=([^&]*)/g, m;
// Creates a map with the query string parameters
while (m = re.exec(queryString)) {
queryParameters[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
// Update w and h
queryParameters['w'] = 200;
queryParameters['h'] = 200;
Now you can either create a new URL:
var url = window.location.protocol + '//' + window.location.hostname + window.location.pathname;
// Build new Query String
var params = $.param(queryParameters);
if (params != '') {
url = url + '?' + params;
}
OR you could just use the params to cause browser to reload right away:
location.search = params;
OR do whatever you want with :)
You could do something like this:
// If key exists updates the value
if (location.href.indexOf('key=') > -1) {
location.href = location.href.replace('key=current_val', 'key=new_val');
// If not, append
} else {
location.href = location.href + '&key=new_val';
}
Regards
URI.js seems like the best approach to me
http://medialize.github.io/URI.js/
let uri = URI("http://test.com/foo.html").addQuery("a", "b");
// http://test.com/foo.html?a=b
uri.addQuery("c", 22);
// http://test.com/foo.html?a=b&c=22
uri.hash("h1");
// http://test.com/foo.html?a=b&c=22#h1
uri.hash("h2");
// http://test.com/foo.html?a=b&c=22#h2
Alright, If you are someone like me who only wants to update query string on URL without reloading the page. try following code
updateQueryString('id',post.id)
function updateQueryString(key, value) {
if (history.pushState) {
let searchParams = new URLSearchParams(window.location.search);
searchParams.set(key, value);
let newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + searchParams.toString();
window.history.pushState({path: newurl}, '', newurl);
}
}
$('.desktopsortpriceHandler').on('change', function(){
let price_id = $(this).val()
$('.btn_product_locality_filter').attr("href", function (i, val) {
// if p is in between of url
val = val.replace(/p=.*?&/i, ""); ----> this will help to get the parameter using regex and replace it with ""
// if p at the end of url
val = val.replace(/&p=.*?$/i, ""); ----> this will help to get the parameter using regex and replace it with ""
return val + `&p=${encodeURIComponent(price_id.toString())}`; ---> then you can add it back as parameter with new value
});
})
i'm using this
function UpdateUrl(a,b,c,pagetitle) {
var url = window.location.href;
var usplit = url.split("?");
var uObj = { Title: pagetitle, Url: usplit[0] + "?w=a&h=b&bg=c};
history.pushState(uObj, uObj.Title, uObj.Url);
}

JQuery with several Elements issue

i got an anchor in the DOM and the following code replaces it with a fancy button. This works well but if i want more buttons it crashes. Can I do it without a for-loop?
$(document).ready(buttonize);
function buttonize(){
//alert(buttonAmount);
//Lookup for the classes
var button = $('a.makeabutton');
var buttonContent = button.text();
var buttonStyle = button.attr('class');
var link = button.attr('href');
var linkTarget = button.attr('target');
var toSearchFor = 'makeabutton';
var toReplaceWith = 'buttonize';
var searchButtonStyle = buttonStyle.search(toSearchFor);
if (searchButtonStyle != -1) {
//When class 'makeabutton' is found in string, build the new classname
newButtonStyle = buttonStyle.replace(toSearchFor, toReplaceWith);
button.replaceWith('<span class="'+newButtonStyle
+'"><span class="left"></span><span class="body">'
+buttonContent+'</span><span class="right"></span></span>');
$('.buttonize').click(function(e){
if (linkTarget == '_blank') {
window.open(link);
}
else window.location = link;
});
}
}
Use the each method because you are fetching a collection of elements (even if its just one)
var button = $('a.makeabutton');
button.each(function () {
var btn = $(this);
var buttonContent = btn.text();
var buttonStyle = btn.attr('class');
var link = btn.attr('href');
var linkTarget = btn.attr('target');
var toSearchFor = 'makeabutton';
var toReplaceWith = 'buttonize';
var searchButtonStyle = buttonStyle.search(toSearchFor);
...
};
the each method loops through all the elements that were retrieved, and you can use the this keyword to refer to the current element in the loop
var button = $('a.makeabutton');
This code returns a jQuery object which contains all the matching anchors. You need to loop through them using .each:
$(document).ready(buttonize);
function buttonize() {
//alert(buttonAmount);
//Lookup for the classes
var $buttons = $('a.makeabutton');
$buttons.each(function() {
var button = $(this);
var buttonContent = button.text();
var buttonStyle = button.attr('class');
var link = button.attr('href');
var linkTarget = button.attr('target');
var toSearchFor = 'makeabutton';
var toReplaceWith = 'buttonize';
var searchButtonStyle = buttonStyle.search(toSearchFor);
if (searchButtonStyle != -1) {
newButtonStyle = buttonStyle.replace(toSearchFor, toReplaceWith);
button.replaceWith('<span class="'
+ newButtonStyle
+ '"><span class="left"></span><span class="body">'
+ buttonContent
+ '</span><span class="right"></span></span>');
$('.buttonize').click(function(e) {
if (linkTarget == '_blank') {
window.open(link);
} else window.location = link;
}); // end click
} // end if
}); // end each
}

Categories