So, I really need some help. I've done extensive searches, and some of the solutions I've found are great but aren't working for me, so here goes...
When someone comes to my site, they are going to click on a link which will pass a URL to "recipes.html"... For Example, if they clicked on "Ancho Chile Sauce", the URL would be:
blahblahblah.com/recipes.html?r=Ancho-Chile-Sauce
This parameter is actually the name of a JPEG in the folder "Recipes", of course with the ".jpg" extension
I need to take this parameter into a string and add "Recipes/" before it and ".jpg" after it, and then alter the source of an image tag in my html document to display the new dynamically called recipe image.
I thought I'd done this, but nothing seems to be working. There's obviously something I'm doing wrong in my Javascript, because my markup works fine and the url with parameter is getting passed.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Recipes</title>
<link href="mobi-styles.css" rel="stylesheet" />
<script type="text/javascript">
function getParam ( sname )
{
var params = location.search.substr(location.search.indexOf("?")+1);
var sval = "";
params = params.split("&");
// split param and value into individual pieces
for (var i=0; i<params.length; i++)
{
temp = params[i].split("=");
if ( [temp[0]] == sname ) { sval = temp[1]; }
}
return sval;
}
window.onload = changePic();
var param = getParam("r");
var recipeName = "Recipes/"+param+".jpg";
function changePic() {
document.getElementById("recipe").src=recipeName;
}
</script>
</head>
<body>
<img class"resizer" id="recipe" src="" />
</body>
</html>
Please help! Me love you long time!
So you can pass an any string:
and so on...
This is what I use to collect URL variables:
JQUERY EXTENSION
And you can use it like this:
If you don't use Jquery, a Javascript only solution would be:
And can be used like this:
remove the
()
. When attaching events, you assign a function, not the result of a function call. What you did was callchangePic()
, returnedsval
and assigned the value ofsval
towindow.onload
- that's wrong.And move
window.onload = changePic
at the bottom so JSLint won't be mad. It's best practice to declare functions up top before using them, even when there is hoisting.Change this:
To this:
I have written a little script that gives me access to the url paramater in the past and it can be very effective. it runs in the beginning of the file so you can access them anytime.
Now you can access the parameters you want:
or
if the parameter are repeated multiple times then it is stored as an array;
the name property becomes an array
I hope this can help you