change the value of parameter in URL - javascript

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.

Related

Pass 2 Functions Through One OnChange Event - With HREF on both Functions

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);
}

Redirect url if checkboxes are selected

I have some problem with redirecting urls after checkboxes are selected. I am using document.location for this, but this doesn´t work in my code. I'm trying to fix it, but without success.
This is the part of my code which doesn't work:
function objednat() {
var adress = "";
if (document.getelementbyid('BoxtarifVolani1').checked == true) {
adress += "#tarifVolani1";
}
window.location = 'http://www.investcon.webinpage.cz/cz/objednat-tarif-dobijeci-cislo/' + adresa;
}
I want to redirect this to a form, which will be filled with the selected values. I don't know why, but this document.location doesn't work in the code.
This is the part of the code I use in the formula for grabbing the hash from the url.
<script type="text/javascript">
if(window.location.hash) {
//set the value as a variable, and remove the #
var hash_value = window.location.hash.replace('#', '');
if (tarifVolani1 == true) {
document.getelementbyid('BoxtarifVolani1").checked = true;}
....
</script>
What am I doing wrong?
Whatever you have done is right, except, the function name is wrong case:
Change getelementbyid to getElementById.
Change adresa to adress.
Code:
function objednat() {
var adress = "";
if (document.getElementById('BoxtarifVolani1').checked == true) {
adress += "#tarifVolani1";
}
window.location = 'http://www.investcon.webinpage.cz/cz/objednat-tarif-dobijeci-cislo/' + adress;
}
jQuery way of doing it
function objednat() {
var adress = "";
if ($('#BoxtarifVolani1').is(':checked')) {
adress += "#tarifVolani1";
}
window.location = 'http://www.investcon.webinpage.cz/cz/objednat-tarif-dobijeci-cislo/'+adress;
}
For your ref: jQuery :checked Selector

jQuery insert/remove text at specific position in input field/textarea

I am trying to do similar thing as YouTube has when you are embeding a video and you want to get a code. You can click on checkboxes or select size and it dynamically changes the value of input field.
Does somebody have idea how to do it?
I managed to write a code that is replacing the width correctly, but I dont know how to make a code that would add &scheme=XXX at the end of the link or remove it if user selects no color scheme.
This is the code for width,I dont think its best one, but works:
$("#width").on("change keyup", function(){
var width = $(this).val();
if (width){
$("#embed-text").val($("#embed-text").val().replace(/ (width\s*=\s*["'])[0-9]+(["'])/ig, ' width=\''+width+'\''));
}
});
Here is textarea which I am trying to change and inputs I'm using for it:
The ID is taken from PHP, in actual textarea that jQuery sees the ".$id." is actual number
<textarea class='clean' id='embed-text'><iframe src='http://my.url/embed/?r=".$id."' width='600' height='".$height."' frameborder='0' marginwidth='0' marginheight='0' allowtransparency='true'></iframe></textarea>
<div style='padding-right: 10px; display: inline-block;'>
Color scheme:
<select id='schemes' class='clean'>
<option value='-'>None</option>
<option value='xxx'>Xxx</option>
</select>
</div>
<div style='padding-right: 10px; display: inline-block;'>
Width: <input type='number' min='250' max='725' value='600' id='width' class='clean'>
</div>
When user does not select any scheme (or changes from XXX to None), I want link in textarea (iframes src) to be like this:
http://my.url/embed/?r=X
But when he selects any scheme, i would like it to look like this:
http://my.url/embed/?r=X&scheme=XXX
I actually have no idea how to do this. Tried googling for more than hour, but I don't know what the ID will be (to identify position where to add the string), thats PHP value and I cant pass it to external script file, so I tried to find if I can insert something at specific position (ie.: 15th character from start) with JS, but could not find anything.
Thanks.
I separate some functions in order to keep the code clean check this I think that is what you were looking for JsFiddle
var generateUrl = function(id,colorScheme) {
var baseUrl = "http://my.url/embed/?";
var url = baseUrl.concat("r="+id);
if (colorScheme != null && colorScheme != '')
url = url.concat("&scheme="+colorScheme);
return url;
};
var changeUrl = function(id, colorScheme) {
var url = generateUrl(id, colorScheme);
var srcPattern = "src='(.*?)'";
var embedText = $("#embed-text").val();
var newEmbedText = embedText.replace(new RegExp(srcPattern),"src='"+url+"'");
$("#embed-text").val(newEmbedText);
};
var changeWidth = function(newWidth) {
var widthPattern = "width='([0-9]*)'";
var embedText = $("#embed-text").val();
var newEmbedText = embedText.replace(new RegExp(widthPattern),"width='"+newWidth+"'");
$("#embed-text").val(newEmbedText);
};
var getURLParameter = function(url,parameterName) {
return decodeURIComponent((new RegExp('[?|&]' + parameterName + '=' + '([^&;]+?)(&|#|;|$)').exec(url)||[,""])[1].replace(/\+/g, '%20'))||null
};
var getId = function() {
var urlPattern = "src='(.*?)'";
var embedText = $("#embed-text").val();
var url = embedText.match(new RegExp(urlPattern))[1];
var id = getURLParameter(url, 'r');
return id;
};
$("#width").on("change keyup", function(){
var width = $(this).val();
var colorScheme = $(schemes).val();
changeWidth(width);
changeUrl(getId(),colorScheme);
});
And i removed the value '-' for the first option just leave it in blank.

Passing an URL parameter to a href link using Javascript

I have the following code working to pass a URL parameter to a form tag:
<script type="text/javascript">
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];
}
}
}
function onLoad() {
var value = getQueryVariable("ID");
var e = document.getElementById('your-field');
e.value = value;
}
</script>
And...
<body onload="onLoad()">
<!-- your form and hidden field goes here -->
<input type="hidden" name="your-field" id="your-field" />
How can I pass the same value to an HTML link so that the end result would be:
<a href="http://www.mysite.com?source=[ID]" >
Where [ID] is the whatever piece of code that is needed to add the parameter to the link?
Thanks in advance.
You should give an id to you link, like this:
<a id="YOUR_ID" href="#" >
And then you have two ways to solve the problem, use pure Javascript or use jQuery:
IF you use jquery you can use your onLoad function and inside inject the following:
var url = "http://www.mysite.com?source=" + value;
$("#YOUR_ID").attr("href",url)
OR using pure javascript:
var url = "http://www.mysite.com?source=" + value;
var element = document.getElementById('YOUR_ID');
element.setAttribute("href",url)
Change the function onload to this:
function onLoad() {
var value = getQueryVariable("ID");
var e = document.getElementById('your-field');
e.value = value;
var url = "http://www.mysite.com?source=" + value;
var element = document.getElementById('YOUR_<A>_ELEMENT_ID');
element.setAttribute("href",url)
}
I'm using the piece of code that Joao Almeida suggested so his example using jQuery works good too.
Good Luck!

How to add a parameter to the URL?

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>

Categories