Replacing two elements in a URL in javascript - javascript

Bit of a javascript newbie so not sure if this question is easy or impossible.
Am working on a site with different testing environments and have made a greasemonkey script to make a set of buttons to switch from one to another:
if (/^(.*?)\www.mysite.com(.*)$/.test(document.location.href)) {
document.location.href = RegExp.$1+"iww1.mysite.com"+RegExp.$2
}
This has been working except for some URLs have a search string ID that also needs changing to a different number too.
&storeId=15162
I feel like I've exhausted my limited knowledge, by adding another if function within the {} to adding various replace functions, all to no avail.
If this makes sense and anyone can help it would be much appreciated.
Cheers

Your first problem is that the location object is magical: assigning to it, or to any of its properties, causes the browser to navigate to the assigned URL. Since this will typically stop your script, you won't be able to do it twice. Instead, you should store the intermediate URL in some other variable, and only assign it back to location.href once you're ready to move to the new page.
Also, you didn't specify how the new "search string ID" should be calculated, so I just assumed that you have some function, named e.g. getNewStoreID(), that will return the new ID when you give it the old one. Given such a function, this code should do it:
var siteRegExp = /www\.mysite\.com/;
var paramRegExp = /([?&]storeId)=(\d+)/;
if ( siteRegExp.test( location.href ) ) {
var href = location.href.replace( siteRegExp, "iww1.mysite.com" );
var match = paramRegExp.exec( href );
if ( match ) {
href = href.replace( paramRegExp, "$1=" + getNewStoreID( match[2] ) );
}
location.href = href; // navigate to the new URL!
}

Related

Javascript variable equals specific URL

I'm trying to get this conditional statement to work, but having no luck
<body onload="HashTagInsert()">
function HashTagInsert() {
var hash="window.location";
if (hash==="http://www.address.com#anchor1")
{
document.getElementById("insert-text").innerHTML="<h2>Title</h2><p>body text</p>";
}
else if (hash==="http://www.url.com/foler/code/page.html#anchor2")
{
document.getElementById("insert-text").innerHTML="<h2>Title</h2><p>body text</p>";
}
else ()
{
document.getElementById("insert-text").innerHTML="something else text"
}
}
</body>
If you want the hash variable to be the value of the window.location object, then don't put quotes around the object name as that will turn it into a string literal.
var hash = window.location;
I recommend not calling the variable hash though, as that could be confused with window.location.hash, which contains the fragment ID component of the URL.
Don't add quotes around window.location.
var hash = window.location.href;
If you want to compare your current window location with some string you need to set the "hash" variable correctly:
var hash = window.location;
but I am not sure if I got your problem.
In case that your javascript can not set your html properly, there is also a timing problem. It depends when your javascript gets called. Before or after your DOM has been rendered. Because if your javascript is executed before your DOM (and your element '#insert-text') is rendered, you wont be able to select this DOM element.
And ... but this is perhaps just my opinion, is is pretty uncool to have masses of if / else if / else constructions in your code.
You might want to map some url and text so that you do not need to make your life harder than it is.
for example:
var html;
var mapping = {
"http://www.address.com#anchor1":"<h2>Yeah</h2><p>Baby</p>",
"http://www.address.com#anchor2":"<h2>Cool</h2><p>Tomato</p>",
"default": "<h2>Woops</h2><p>Honolulu rocks</p>"
}
mapping[window.location.href] ? html = mapping[window.location.href] : html = mapping['default'];
document.getElementById("insert-text").innerHTML=html;

Using .append() in if statments?

I am trying to use .append() with if statements, I have a lot of them maybe 10. What I'm trying to do is add to a div if something happens. if A is less then 5 I want to add to the div, so on and so on. .append() works good for me if I put all of the things I want to add in one .append(). But if I try to do it separately it will not work for me. I don't know what I will be adding a head of time, it depends on user data so I can't add everything I want in one .append(). My code is long so I have put a fiddle below. I know i may have other issues with this code but, just asking about .append() or a way to add to my div like i want
if(k3a<5) {
msg3="need to work on q3"
var c = $('<p>'+msg3+'</p>')
$('#output1').append(c);
$output1.text(msg3);
}
if(k4a<5) {
msg4="need to work on q4"
var e = $('<p>'+msg4+'</p>')
$('#output1').append(e);
$output1.text(msg4);
}
if(k5a<5) {
msg5="need to work on q5"
var e = $('<p>'+msg5+'</p>')
$('#output1').append(e);
$output1.text(msg5);
}
I know I can do something like below, but I need to add them one by one if the condition is meet, not at once.
if (k1 < 10) {
msg1 = "This will not space like a want.<br/>";
msg2 = "I don know why not.<br/>";
msg3 = "How come.<br/>";
var e = $('<p>'+msg1+'</p>'+'<p>'+msg2+'</p>'+'<p>'+msg3+'</p>');
$('#output1').append(e);
}
http://jsfiddle.net/G24aQ/21/
This looks like you don't understand what the code is doing; (assuming $output1 is $('#output1)) current code is (just one part)
msg4="need to work on q4"; // set global variable `msg4`
var e = $('<p>'+msg4+'</p>'); // set local variable `e`
$('#output1').append(e); // append html to element
$output1.text(msg4); // re-set content of element as text
You most likely want just
var msg4="need to work on q4", // set local variable `msg4`
e = $('<p>'+msg4+'</p>'); // set local variable `e`
$('#output1').append(e); // append html to element
What is $output1? That should be a variable, but you don't assign anything to it. Also, there is no need to use $() to put HTML into just for the sake of assigning it to your c or e variable. $() gets content. You just need to make a String, like:
var c = '<p>'+msg3+'</p>';
although I would have var e, c above all your code, if I was going to reuse it, so you don't have to rewrite var, and I wouldn't store msg3 in a variable at all. My code would contain, something like:
var out1 = $('#output1');
if(k3a<5)out1.append('<p>need to work on q3</p>');
if(k4a<5)out1.append('<p>need to work on q4</p>');
if(k5a<5)out1.append('<p>need to work on q5</p>');
Your code is different on you jsFiddle page. For instance, k3a does not exist. Don't redefine var total in your code, either. There may be more problems with your code, but this should put you on the right path.
you may find it easier to define a small function to output the messages. something like
function showMessage( strMsg, targetID ) {
$('#'+targetID).empty().append("<p>" + strMsg + "</p>");
}
and call it using
showMessage( "message one", "output" );
showMessage( "message two", "output1" );
This way when you decide you want to display them in another fashion, you only have to change it in one place.

html link variable

Is it possible to pass two variables through to another html page through a link?
For example... I have a directory page where when a user clicks a store link, it links to another html page with the map centered on the specific store. The function that centers the map on the store takes two variables, storeID, storeName. There are hundreds of stores and currently I would have to manually create each store page separately by hardcoding those two variables so that each page loads slightly differently. Is there a way to pass these two variables with a link, to avoid many different html pages?
Perhaps something along the lines of <a href "thisPage.html", var1, var2>?
ex. code
thispage.html
var1;
var2;
function myFunc(var1, var2) {
~~~
}
Not like that, but you can use URL parameters.
thisPage.html?var1=foo&var2=bar
Then you can read them on the second page. I like to use this function for that:
function gup( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
From http://www.netlobo.com/url_query_string_javascript.html
So on your second page, you can just do gup("var1") and you will get foo.
Use a query string.
In a URL a ? indicates the start of the query. It consists of a series of key=value pairs separated by & characters.
The encodeURIComponent function will escape text for inserting as a key or a value.
You can then assign it to the href attribute of the link element or set location.href to it.

Moving inline code into function, with object name generation

I am customizing Denis Gritcyuk's Popup date picker.
This pop-up script uses inline Javascript in a href link, to set the selected date into the input field, in the parent window, that is was called for. An example URL looks like:
<a href="javascript:window.opener.document.formname.field.value='03-10-2011';
window.close();">3</a>
The input field name, (e.g. document.formname.field), is passed to the script as a string parameter.
I would like to add things done when that link is clicked (e.g. change background color of field, set flag, etc.). So while this DOES work, it's getting ugly fast.
<a href="javascript:window.opener.document.formname.field.value='03-10-2011';
window.opener.document.formname.field.style.backgroundColor='#FFB6C1';
window.close();">3</a>
How would I move these inline commands into a JS function? This would give me much cleaner URLs and code. The URL would now look something like
3
with a function like (this example obviously does NOT work):
function updateField (str_target, str_datetime) {
var fieldName = "window.opener" + str_target;
[fieldName].value = str_datetime;
[fieldName].style.backgroundColor = '#FFB6C1';
// Set flag, etc.
window.close();
}
So any suggestions on how this can be done, please?
I'd prefer to hide the dom path tracing back from the current window back to the opener. It's appropriate to bake that into the function since the function will always be used in the context of that child popup. Then your function call is cleaner and more readable. Obviously, replace "myField" with the ID of the field you're intending to update.
3
function updateField ( str_date, str_fieldname ) {
var fieldToUpdate = document.getElementById( str_fieldname );
fieldToUpdate.value = str_date;
fieldToUpdate.style.backgroundColor = '#FFB6C1';
// Set flag, etc.
window.close();
}
You're acessing the property incorrectly. Try:
function updateField (str_target, str_datetime) {
var fieldName = window.opener;
str_target = str_target.split('.');
for (var i = 0; i < str_target.length; i++)
fieldName = fieldName[str_target[i]];
fieldName.value = str_datetime;
fieldName.style.backgroundColor = '#FFB6C1';
// Set flag, etc.
window.close();
}
The bracket notation ([]) is only used for properties of objects, not objects themselves. If you found my post helpful, please vote for it.
You can build a string and evaluate it as code using the eval function, but I would recommend against it.
There are a couple of things wrong with your code:
You cannot use the [] operator in a global context, you have to suffix it on an object, so you can say window["opener"] and this will be equivalent to window.opener, but there is no such thing as simply ["window"]
When navigating nested properties, as in window.opener.document you cannot navigate multiple levels using the [] operator. I.e. window["opener.document"] is not allowed. You must use window["opener"]["document"] instead.

Calling javascript variable parameters from global function on the <a href > onclick event

The I wrote in the <a href='javascript:newsdatainfo(document.xmldoc,...see below. But it still does not work.
var dataxml = unescape(xml);
var xmldoc = getDomAdapter().parseXml(dataxml);
var rootnode = xmldoc.getElementsByTagName('result_set')[0];
var newsresult = rootnode.getElementsByTagName('item');
var pages = Math.round(newsresult.length / 10);
var pagesref;
for (var p=1; p <= pages;p++){
if (p==1)
pagesref = pagesref+"<a href='javascript:newsdatainfo(document.xmldoc,document.newsresult,6,10)' >"+p+"</a> | ";
Echoing other responses I don't know quite what you're asking here. In particular never say "it doesn't work - state what actions you performed, what your expected output was and what your actual output was. Though anyway:
You shouldn't use a javascript: prefix in a href; you should actually use the onclick event that you referenced in your question title.
You can just use xmldoc and rootnode unprefixed.
If you don't want the hyperlink to actually go anywhere, make sure you return false from the onclick handler to prevent the click from being handled. Also set the URL to "#" (which will typically point to the top of the current page), so that the link will degrade gracefully with Javascript disabled and so that the address in the status bar on hover makes sense (unless you want to override that too).
I hope that code ends abruptly, since looping over all elements just to perform some action on the first one is suboptimal, to say the least.
Thus I believe your last line could be written as
pagesref = pagesref+"<a href='#' onclick='newsdatainfo(xmldoc,newsresult,6,10); return false' >"+p+"</a> | ";
and things might work as you expect, however that may be.

Categories

Resources