Javascript variables cannot...? - javascript

I'm working up to PREV/NEXT buttons that will get the current pathname, find it in an array, and increment its index to output a redirect or link, not sure if my terminology is correct. I have it pretty much figured out, but I ran into this one question which is bugging me. There's a simple answer no doubt invisible to noobs but I don't know how to research it more than what I already did. Not a big deal to my code, but why can't I use a variable in the 2nd example; why do I have to spell out the redirect statement?
Example One: This redirect works.
<button onclick="pp();">PREV1</button>
<script>
function pp() {
var qq = window.location.pathname;
if (qq == '/F:/0-website/wwwtesting/javascript_variables_cannot.html') {
window.location.pathname = '/F:/0-website/webpage.html';
}
};
</script>
Example Two: I don't need the conditional as used in the last example, but without it the redirect doesn't work. What's the difference to JS? All I changed was to remove the conditional, and the alert works but the redirect doesn't.
<button onclick="rr();">PREV2</button>
<script>
function rr() {
var yy = window.location.pathname;
yy = '/F:/0-website/webpage.html';
};
/*alert(yy);*/
</script>

Related

How to find URL domain using JavaScript

I was working on how to find a URL's domain, and thanks to my previous question, I came to this answer:
var domain = (location.host)
var arr=domain.split(".")
extension=arr[arr.length-1]
if(extension=="cnn")
alert("true");
However, I have 2 problems:
It works fine untill you come across to a site with extension co.uk.
Is there a way to count . from the start and not from the end?
For example, for the website www.cnn.com, it'd start counting from the www, and not from the com.
Okay, here's the edit to make you understand how it works.
Say, your website is "www.cnn.co.uk". If you understand array, this line would return you the array of 4 elements delimited by '.'
var arr=domain.split(".")
i.e. [www, cnn, co, uk];
Now it's really upto you what element you want out of this array. If you know the element name, and you want to retrieve cnn, you can do
`extension = arr[1];`
You can also iterate over an array to get each element.
extension = arr[0];
it will return you www.
Use this function:
function GetDomainName() {
if (location.host.split('.')[0] == 'www') {
return location.host.split('.')[1];
} else {
return location.host.split('.')[0];
}
}
Call it like this:
var domainName=GetDomainName();
But remember, this will not work in subdomains like
programmers.stackexchange.com
Demo: http://jsfiddle.net/j7VP6/

Javascript Function arguments as variables

Firstly i would like to note this is my first time using this site so if I do something incorrectly, i am sorry. Secondly i am intermediate at JavaScript but have only been truly been coding with for 3 days and am using it in an incremental game (more for myself to learn than others as there are quite a few out there). I've been doing pretty good and learning more as i go.
My problem is that I've gotten stuck using a function with arguments, my code looks like this:
<button onClick="getStorg(gargAmm,'gargAmm')"> Get Garage </button>Ammount: <span id="gargAmm">0<br />
Which is the HTML that launces the Function:
var gargAmm = 0;
function getStorg(buildAmm,buildID)
{
buildAmm = buildAmm + 1;
document.getElementById(buildID).innerHTML = buildAmm;
}
The display will make the "Amount:" go up to one when the button is first clicked, but then stalls. I've tried rearranging all sorts of variables and such but i just don't know why this doesn't work. Can anyone help?
What you're doing is you're using the Global variable value
var gargAmm = 0;
Whenever you call the function it uses the same value as zero and increments it.
So your getting the value as 1 and its not incrementing further.
I have tried an another approach to solve your issue have a look at it.
<button onClick="getStorg('gargAmm')">
Get Garage
</button>Ammount: <span id="gargAmm">0</span><br />
Here is the javascript
function getStorg(buildID)
{
var d= document.getElementById(buildID);
var t= parseInt(d.innerText);
t=t+1;
document.getElementById(buildID).innerHTML = t;
}
Here the text from the span is taken and converted to int and then incremented the value
and inserted back into span.
Here is the Working fiddle http://jsfiddle.net/p8E4G/
Simple:
function myFunc(a,b) {
b = b || 0;
// b will be set either to b or to 0.
}

Why does this script never run?

I've got the following JavaScript statement, that executes on Page Load:
The variable u1 is populated with one of the following values:
BBSLoan|Accept|PPI+No|60Months
BBSLoan|Refer|PPI+No|60Months
HSBSLoan|Accept|PPI+No|48Months
HSBSLoan|Refer|PPI+No|48Months
I have been informed that the conditions in the conditional statements will never be met - is this true? From what I can see, going on each of the variables, the index that will be returned by indexOf is 0? Unless I am mistaken?
EDIT: Just to clarify, the variable 'u1' will be populated dynamically with any of the 4 strings listed above. The %pu1=!; is actually a macro that will populate this value.
<script language="JavaScript" type="text/javascript">
var u1 = '%pu1=!;';
if (u1.indexOf('BBSLoan|Accept') > -1) {
var pvnPixel = '<img src="http://www.url1.com"/>';
document.writeln(pvnPixel);
}
if (u1.indexOf('BBSLoan|Refer') > -1) {
var pvnPixel2 = '<img src="https://www.url2.com;"/>';
document.writeln(pvnPixel2);
}
if (u1.indexOf('HSBSLoan|Accept') > -1) {
var pvnPixel3 = '<img src="https://www.url3.com;"/>';
document.writeln(pvnPixel3);
}
</script>
Thanks in advance!
EDIT: Just to clarify, the variable 'u1' will be populated dynamically with any of the 4 strings listed above. The %pu1=!; is actually a macro that will populate this value.
This answer is not correct. It will be deleted later, but is being left to prevent this answer from popping up again.
var u1 = '%pu1=!;';
The value of u1 is always '%pu1=!;', since you declare it as that.
Ok I finally got this to work using search instead of indexOf!
Would it make more sense to use a switch statement with a default case, or at a minimum provide an "else" with a default?
Have you tried to put a debugger statement in after var u1 is set, and step through using the client (firefox, chrome, IE, safari all have built in "developer tools" with the ability to step through js code) debugger to see what the value of u1 is?

Exact string match with javascript regex

I'm struggling with what is probably a very simple regex problem. I'm working on a simple prototype and need to know what page I'm on, so I don't reload it if the user clicks a menu widget to navigate to the same view.
I have two URLs the user can switch between:
http://localhost/TestMVC/Larry/LarryTiles
http://localhost/TestMVC/Larry/LarryTilesList
The URLs can also have some trailing querystring items, like this:
http://localhost/TestMVC/Larry/LarryTilesList?filterValue=servers
LarryTiles is giving me the problem. "/\bLarryTiles\b/" worked on Friday (after answers from other questions here) but this doesn't match now. :)
I need to find exactly the strings "LarryTiles" and "LarryTilesList" in these two URLs but can't quite figure out how to do that. The URL changes between my local machine and the various servers where it's hosted, so I can't rely on position.
EDIT: added the example with a trailing querystring, which I'd forgotten. Sorry :(
You can get the last path segment of an URL like this:
function getLastPathSegment(url) {
var match = url.match(/\/([^\/]+)\/?$/);
if (match) {
return(match[1]);
}
return("");
}
// returns "LarryTiles"
getLastPathSegment("http://localhost/TestMVC/Larry/LarryTiles");
// returns "LarryTilesList"
getLastPathSegment("http://localhost/TestMVC/Larry/LarryTilesList");
So, you could do this:
var endPath = getLastPathSegment(window.location.pathname);
if (endPath == "LarryTiles") {
// some code
} else if (endPath == "LarryTilesList") {
// some code
} else {
// some code
}
You can use this code:
str = 'http://localhost/TestMVC/Larry/LarryTiles?filterValue=servers';
if (str.match(/\/([^\/?]+)(?=\/$|\?|$)/)) {
if (match[1] == 'LarryTiles')
alert('LarryTiles found');
else if (match[1] == 'LarryTilesList')
alert('LarryTilesList found');
}
Seems like what you explained works, otherwise try this: http://jsfiddle.net/Wfz9d/
Do you have a case-sensitivity issue?

Javascript will not combine these together

I have this js code
elem=$(this);
var tester_names="";
tester_names=$("#release_tester_tokens").val();
alert(tester_names)
if (elem.attr('checked')==true)
**tester_names=tester_names+", "+ elem.attr("title");**
alert(elem.attr("title"))
alert(tester_names)
I want to have tester_names=tester_names+", "+ elem.attr("title"); to have the combination of testers_names (a,b,c,d,e) and elem.attr("title") (f) to become (a,b,c,d,e,f)
The alerts that I used is for debugging to see what values are stored in the variable.. They all store correctly, but they don't combine together when I call the bolded function... I just want to know why. I am using formtastic textarea instead of the normal textbox... do I have to adjust to that? Or maybe what the tester_names and elem.attr are outputting are of different type?
I tried it using this type of code (this is nearly the same with different variable names
function updateTextArea() {
var allVals = [];
$('.taglist :checked').each(function(i) {
allVals.push( $(this).val());
});
$('#video0_tags').val(allVals).attr('rows',allVals.length) ;
}
$(function() {
$('.taglist input').click(updateTextArea);
updateTextArea();
});
});​
why does this add to checkbox values to the textarea perfectly whenever I check checkboxes when mine just outputs same results before and after using the starred function?
(I don't understand why ppl keep voting this down... its seems like a decent question after the first mishap and fix) :S
Use elem.attr('checked')=='checked' in if statement. There is no case elem.attr('checked')==true will be true. So the body of your if , will never be executed.

Categories

Resources