My current URL is: http://something.com/mobiles.php?brand=samsung
Now when a user clicks on a minimum price filter (say 300), I want my URL to become
http://something.com/mobiles.php?brand=samsung&priceMin=300
In other words, I am looking for a javascript function which will add a specified parameter in the current URL and then re-direct the webpage to the new URL.
Note: If no parameters are set then the function should add ? instead of &
i.e. if the current URL is http://something.com/mobiles.php then page should be re-directed to http://something.com/mobiles.php?priceMin=300
instead of http://something.com/mobiles.php&priceMin=300
try something like this, it should consider also cases when you already have that param in url:
function addOrUpdateUrlParam(name, value)
{
var href = window.location.href;
var regex = new RegExp("[&\\?]" + name + "=");
if(regex.test(href))
{
regex = new RegExp("([&\\?])" + name + "=\\d+");
window.location.href = href.replace(regex, "$1" + name + "=" + value);
}
else
{
if(href.indexOf("?") > -1)
window.location.href = href + "&" + name + "=" + value;
else
window.location.href = href + "?" + name + "=" + value;
}
}
then you invoke it like in your case:
addOrUpdateUrlParam('priceMin', 300);
Actually this is totally trivial, because the javascript location object already deals with this. Just encapsulate this one-liner into a function to re-use it with links etc:
<script>
function addParam(v) {
window.location.search += '&' + v;
}
</script>
add priceMin=300
There is no need to check for ? as this is already the search part and you only need to add the param.
If you don't want to even make use of a function you can write as so:
add priceMin=300
Keep in mind that this does exactly what you've asked for: To add that specific parameter. It can already be part of the search part because you can have the same parameter more than once in an URI. You might want to normalize that within your application, but that's another field. I would centralize URL-normalization into a function of it's own.
Edit:
In discussion about the accepted answer above it became clear, that the following conditions should be met to get a working function:
if the parameter already exists, it should be changed.
if the parameter already exists multiple times, only the changed copy should survive.
if the parameter already exists, but have no value, the value should be set.
As search already provides the search string, the only thing left to achieve is to parse that query-info part into the name and value pairs, change or add the missing name and value and then add it back to search:
<script>
function setParam(name, value) {
var l = window.location;
/* build params */
var params = {};
var x = /(?:\??)([^=&?]+)=?([^&?]*)/g;
var s = l.search;
for(var r = x.exec(s); r; r = x.exec(s))
{
r[1] = decodeURIComponent(r[1]);
if (!r[2]) r[2] = '%%';
params[r[1]] = r[2];
}
/* set param */
params[name] = encodeURIComponent(value);
/* build search */
var search = [];
for(var i in params)
{
var p = encodeURIComponent(i);
var v = params[i];
if (v != '%%') p += '=' + v;
search.push(p);
}
search = search.join('&');
/* execute search */
l.search = search;
}
</script>
add priceMin=300
This at least is a bit more robust as it can deal with URLs like these:
test.html?a?b&c&test=foo&priceMin=300
Or even:
test.html?a?b&c&test=foo&pri%63eMin=300
Additionally, the added name and value are always properly encoded. Where this might fail is if a parameter name results in an illegal property js label.
if(location.search === "") {
location.href = location.href + "?priceMin=300";
} else {
location.href = location.href + "&priceMin=300";
}
In case location.search === "", then there is no ? part.
So add ?newpart so that it becomes .php?newpart.
Otherwise there is a ? part already.
So add &newpart so that it becomes .php?existingpart&newpart.
Thanks to hakre, you can also simply set it like:
location.search += "&newpart";
It will automatically add ? if necessary (if not apparent, it will make it ?&newpart this way, but that should not matter).
I rewrite the correct answer in PHP:
function addOrUpdateUrlParam($name, $value){
$href = $_SERVER['REQUEST_URI'];
$regex = '/[&\\?]' . $name . "=/";
if(preg_match($regex, $href)){
$regex = '([&\\?])'.$name.'=\\d+';
$link = preg_replace($regex, "$1" . $name . "=" . $value, $href);
}else{
if(strpos($href, '?')!=false){
$link = $href . "&" . $name . "=" . $value;
}else{
$link = $href . "?" . $name . "=" . $value;
}
}
return $link;
}
I hope that help's someone...
There is an more elegant solution available, no need to write your own function.
This will add/update and take care of any ? or & you might need.
var params = new URLSearchParams(window.location.search);
params.set("name", "value");
window.location.search = params.toString();
var applyMinPrice = function(minPrice) {
var existingParams = (location.href.indexOf('?') !== -1),
separator = existingParams ? '&' : '?',
newParams = separator + 'priceMin=' + minPrice;
location.href += newParams;
}
If you're having the user fill out a textfield with a minimum price, why not let the form submit as a GET-request with a blank action? IIRC, that should do just what you want, without any javascript.
<FORM action="" method="get">
<P>
<LABEL for="brand">Brand: </LABEL>
<INPUT type="text" id="brand"><BR>
<LABEL for="priceMin">Minimum Price: </LABEL>
<INPUT type="text" id="priceMin"><BR>
</P>
use var urlString = window.location to get the url
check if the url already contains a '?' with urlString.indexOf('?'), -1 means it doesnt exist.
set window.location to redirect
this is like 101 of javascript. try some search engines!
<html>
<body>
..
..
..
<?php
$priceMinValue= addslashes ( $_GET['priceMin']);
if (!empty($priceMin)) {
$link = "currentpage.php?priceMin=". $priceMinValue;
die("<script>location.href = '".$link. "'</script>");
}
?>
</body>
</html>
Related
I have asked something similar in the past but was able to resolve it by separating the functions by events. I need to be able to pass 2 href events in one Onchange Event because it is a dropdown, OR I need to be able to tie the second function into another Event.
This works only when an alert() is inserted. Once I take the alert() out it does not work. I've tried to supress the alert while still keeping it in the code and it works fine. I do not want the alert but I want the results.
HTML Here:
<select id="PartList" class="form-control form-control-lg ml-0" onChange="SelectMain();">
JavaScript Here
function sList() {
var pl = document.getElementById("PartList");
var value = pl.options[pl.selectedIndex].value;
var text = pl.options[pl.selectedIndex].text;
str = 'URL1 HERE='+ "'" + text + "'" ;
//alert(value);
//alert(text);
window.location.href = str;
}
function SelectValue() {
var pv = document.getElementById("PartList");
var value = pv.options[pv.selectedIndex].value;
str = 'URL2 HERE' + value ;
alert(value);
window.location.href = str;
}
function SelectMain() {
sList();
SelectValue();
}
function alert(message) {
console.info(message);
}
This is resolved, for those that come to this question. The problem wasn't with the JavaScript it was because the device I was sending the commands to couldn't handle the commands that fast. I have incorporated the resolved code with troubleshooting techniques.
function sList() {
var pl = document.getElementById("PartList");
var value = pl.options[pl.selectedIndex].value;
var text = pl.options[pl.selectedIndex].text;
str = 'URL1='+ "'" + text + "'" ;
//str1 = 'http://google.com';
//alert(value);
//alert(text);
window.location.href = str;
//window.open(str1);
}
function SelectValue() {
setTimeout(function(){
var pv = document.getElementById("PartList");
var value = pv.options[pv.selectedIndex].value;
str = 'URL2=' + value ;
//str1 = 'http://aol.com';
//alert(value);
window.location.href = str;
//window.open(str1);
},1000);
}
I am developing a website that works in two languages. I need to change URL to include the selected language.
What I exactly need is:
Pick the current URL
Check if the URL contains any language code
Append the code if not exist or change the code to the selected one if exists
For example, there is an URL for English (default):
http://localhost:11767/Home/resultMain?model=1&&type=1
When a user selects Spanish (es) it should be:
http://localhost:11767/es/Home/resultMain?model=1&&type=1
You can parse the URL with the help of an a element then replace the part you want and re-build the URL :
function addReplaceLangCode(url, langCode) {
var a = document.createElement('a');
a.href = document.getElementById('url').value; // or document.location.href;
var paths = a.pathname.split('/');
paths.shift();
if(paths[0].length == 2) {
paths[0] = langCode;
}else{
paths.unshift(langCode);
}
return a.protocol + '//' +
a.host + '/' + paths.join('/') +
(a.search != '' ? a.search : '') +
(a.hash != '' ? a.hash : '');
}
function onClickReplace() {
document.getElementById('result').innerHTML = addReplaceLangCode( document.location.href, 'es');
}
URL : <input type="text" id="url" style="width:400px" value="http://localhost:11767/Home/resultMain?model=1&&type=1"><input type="button" value="Replace" onclick="onClickReplace()"><br />
Result: <span id="result"></span>
I don't know if it is exactly this, what you want. But JavaScript can obtain URL using object "location". Especially location.pathname is useful for you. You can apply reg-exp on location.pathname to check if URL contain /es/ and if yes, then translate website by proper Ajax requests to your backend.
But generally I recommending to use routing of your backend. The best solution in my opinion - use http headers to inform server about preferred language.
https://www.w3.org/International/questions/qa-accept-lang-locales
Based on #Bulnet Vural's answer above, I wrote the following code because I needed to toggle the language path in and out of the url.
var getOtherLanguageLocation = function (currentUrl, languagePath) {
// based on https://stackoverflow.com/a/42176588/1378980
var anchorTag = document.createElement('a');
anchorTag.href = currentUrl;
var paths = anchorTag.pathname.split("/");
// remove all the empty items so we don't get double slash when joining later.
var paths = paths.filter(function (e) { return e !== '' })
// the language will be at index 1 of the paths
if (paths.length > 0 && paths[0].toLowerCase() == languagePath) {
// remove the language prefix
paths.splice(0, 1);
} else {
// add the language prefix
paths.unshift(languagePath);
}
return anchorTag.protocol + '//' +
anchorTag.host + '/' + paths.join('/') +
anchorTag.search + anchorTag.hash;
};
I have a small javascript issue; I want to reload page with a selected language option value as a get variable.
if I select EN language, the page reload with &lang=EN,
My problem is that I use concat so I get my_url&lang=EN&lang=FR&lang=SP ...
so when I select first EN then FR I want to get my_url&lang=FR not my_url&lang=EN&lang=FR
I want to replace the lang variable not only to add:
<select onchange="javascript:handleSelect(this)">
<option>DE</option>
<option>EN</option>
<option>FR</option>
<option>SP</option>
<option>NL</option>
<option>HR</option>
<option>PL</option>
<option>CZ</option>
</select>
<script type="text/javascript">
function handleSelect(elm)
{
window.location = window.location.href +"?lang="+elm.value;
}
</script>
Try this:
function handleSelect(elm)
{
var href = window.location.href;
if (href.indexOf("lang") > -1)
{
href = href.replace(/(lang)=\w+((?=[&])|)/, "lang="+elm.value);
}
else
{
var char = (href.indexOf("?") == -1 ? "?" : "&");
href+= char + "lang=" + elm.value;
}
window.location.href = href;
}
It should work with any kind of url keeping the params.
Fiddle. In the fiddle I'm using a div instead of the window.location.
try
window.location = window.location.pathname +"?lang="+elm.value;
You could use the replace function:
window.location = window.location.href.match(/lang=/) ? window.location.replace( /lang=(.*){2}/, 'lang=' + elm.value ) : window.location.href + '?lang=' + elm.value;
Reference: http://www.w3schools.com/jsref/jsref_replace.asp
If ?lang= exists, replace it with the new one.
If not, just add the lang parameter.
edit
I like the window.location.pathname solution from Dave Pile, this should be better than checking and replacing something.
edit2
var loc = 'http://test.de/?foo=bar'; // window.location.href;
var seperator = loc.match(/\?/) ? '&' : '?';
var elm = 'DE';
var url = loc.match(/lang/) ? loc.replace(/lang=(.*){2}/, 'lang' + elm ) : loc + seperator + 'lang=' + elm;
document.getElementById('result').innerHTML = url;
<div id="result"></div>
Look at this snippet, you have to change the loc so it should work, also change var url to window.location and elm to your language element.
It checks if parameters exists and change the seperator from ? to &, than if no lang is set, it will set it or if a lang is set, it will replace it.
function handleSelect(elm)
{
var href = window.location.href;
if (href.indexOf("lang") > -1)
window.location.href = href.replace(/(lang)=\w+((?=[&])|)/, "lang="+elm.value);
else
window.location = window.location.href +"&lang="+elm.value;
}
You could use
var currAddress = window.location.href;
var indexOfLang = currAddress.indexOf('lang=');
var tempAddress = currAddress.substring(indexOfLang, indexOfLang+7);
currAddress = currAddress.replace(tempAddress,'lang='+elm.value);
window.location = currAddress;
The number 7 is the length of substring - lang=EN.
I'm attempting to duplicate the original img tag's functionality in custom img tag that will be added to the pagedown converter.
e.g I'm copy the original behavior:
![image_url][1] [1]: http://lolink.com gives <img src="http://lolink.com">
into a custom one:
?[image_url][1] [1]: http://lolink.com gives <img class="lol" src="http://lolink.com">
Looking at the docs the only way to do this is through using the preblockgamut hook and then adding another "block level structure." I attempted doing this and got an Uncaught Error: Recursive call to converter.makeHtml
here's the code of me messing around with it:
converter.hooks.chain("preBlockGamut", function (text, dosomething) {
return text.replace(/(\?\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g, function (whole, inner) {
return "<img src=" + dosomething(inner) + ">";
});
});
I'm not very experienced with hooks and everything so what would I do to fix it? Thanks.
UPDATE: found out that _DoImages runs after prespangamut, will use that instead of preblockgamut
Figured it out! The solution is very clunky and involves editing the source code because I am very bad at regex and the _DoImage() function uses a lot of internal functions only in the source.
solution:
All edits will be made to the markdown.converter file.
do a ctrl+f for the _DoImage function, you will find that it is named in two places, one in the RunSpanGamut and one defining the function. The solution is simple, copy over the DoImage function and related stuff to a new one in order to mimic the original function and edit it to taste.
next to DoImage function add:
function _DoPotatoImages(text) {
text = text.replace(/(\?\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g, writePotatoImageTag);
text = text.replace(/(\?\[(.*?)\]\s?\([ \t]*()<?(\S+?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g, writePotatoImageTag);
return text;
}
function writePotatoImageTag(wholeMatch, m1, m2, m3, m4, m5, m6, m7) {
var whole_match = m1;
var alt_text = m2;
var link_id = m3.toLowerCase();
var url = m4;
var title = m7;
if (!title) title = "";
if (url == "") {
if (link_id == "") {
link_id = alt_text.toLowerCase().replace(/ ?\n/g, " ");
}
url = "#" + link_id;
if (g_urls.get(link_id) != undefined) {
url = g_urls.get(link_id);
if (g_titles.get(link_id) != undefined) {
title = g_titles.get(link_id);
}
}
else {
return whole_match;
}
}
alt_text = escapeCharacters(attributeEncode(alt_text), "*_[]()");
url = escapeCharacters(url, "*_");
var result = "<img src=\"" + url + "\" alt=\"" + alt_text + "\"";
title = attributeEncode(title);
title = escapeCharacters(title, "*_");
result += " title=\"" + title + "\"";
result += " class=\"p\" />";
return result;
}
if you look at the difference between the new _DoPotatoImages() function and the original _DoImages(), you will notice I edited the regex to have an escaped question mark \? instead of the normal exclamation mark !
Also notice how the writePotatoImageTag calls g_urls and g_titles which are some of the internal functions that are called.
After that, add your text = _DoPotatoImages(text); to runSpanGamut function (MAKE SURE YOU ADD IT BEFORE THE text = _DoAnchors(text); LINE BECAUSE THAT FUNCTION WILL OVERRIDE IMAGE TAGS) and now you should be able to write ?[image desc](url) along with ![image desc](url)
done.
The full line (not only the regex) in Markdown.Converter.js goes like this:
text = text.replace(/(!\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g, writeImageTag);
so check the function writeImageTag. There you can see how the regex matching text is replaced with a full img tag.
You can change the almost-last line before its return from
result += " />";
to
result += ' class="lol" />';
Thanks for the edit to the main post.
I see what you mean now.
It is a bit weird how it uses empty capture groups to specify tags, but if it works, it works.
It looks like you would need to add on an extra () onto the regex string, then specify m8 as a new extra variable to be passed into the function, and then specify it as class = m8; like the other variables at the top of the function.
Then where it says var result =, instead of class =\"p\" you would just put class + title=\"" + .......
I'm trying to make a javascript function to change the value of a parameter in the URL with the value inputed in a text box, with no luck. That's because I'm note a code designer but a graph one.
this is the URL where I need to change the "City" parameter:
http://server/ad_new_customer.php?&city=&uri=http://server/adauga_exp.php
I am generating data in the input text box through a MySQL query with jQuery like this:
<input type='text' id='city' name='city' style="width:190px; align:left;" value="<?php echo $city; ?>" /> </td>
<script type="text/javascript">
//change the value of parameter in the URL function
function changeURI(key, value) {
var query = document.location.search.substring(1);
var query_q = query.split("?");
var vars = query_q[1].split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == key) {
vars[i] = pair[0] + "=" + value;
}
}
return vars.join("&");
}
//jQuery making the auto-suggestion query for the input ID
$().ready(function() {
$("#city").autocomplete("core/exp_city.php", {
width: 340,
matchContains: true,
selectFirst: false
}).return(changeURI("city", this.value}));
});
</script>
How can I make it change the value the parameter on selected value?
Please advise, again, a humble designer.
Thank you!
L.E.
I have made an workaround, changed the changeURI() function with this one:
function changeURI(key, value)
{
key = escape(key); value = escape(value);
var kvp = document.location.search.substr(1).split('&');
var i=kvp.length; var x; while(i--)
{
x = kvp[i].split('=');
if (x[0]==key)
{
x[1] = value;
kvp[i] = x.join('=');
break;
}
}
if(i<0) {
kvp[kvp.length] = [key,value].join('=');
}else{
//this will reload the page, it's likely better to store this until finished
document.location.search = kvp.join('&');
}
}
Found on StackOverflow and call it from the jQuery query with the $.result() function:
<script type="text/javascript">
$().ready(function() {
$("#city").autocomplete("core/exp_city.php", {
width: 340,
matchContains: true,
selectFirst: false
}).result(function() {changeURI("city",this.value)});
});
</script>
What error are you getting? are you getting any javascript error? Also, try changing your code to some thing like
url = url.replace(new RegExp("city=", 'g'), "city="+value).
Also, The URL written in the question should not have & before city parameter as the first parameter starts with a ?, so the URL should be :
http://server/ad_new_customer.php?city=&uri=http://server/adauga_exp.php
Check if that was the issue.
In your example, document.location.search.substring(1) is already getting rid of the question mark: it should return &city=&uri=http://server/adauga_exp.php. Then doing a split on "?" and trying to take the second array element should return undefined, because there are no longer any "?" characters. Skip straight to var vars = query.split("&") at that point, and the rest looks okay to me.