Warrior Forum - The #1 Digital Marketing Forum & Marketplace

Warrior Forum - The #1 Digital Marketing Forum & Marketplace (https://www.warriorforum.com/)
-   Programming (https://www.warriorforum.com/programming/)
-   -   Simple javascript needed.... (https://www.warriorforum.com/programming/124672-simple-javascript-needed.html)

Kurt 15th September 2009 03:55 AM

Simple javascript needed....
 
Can any JS experts help me with what I think is a pretty easy script?

What I need is an input box.

User inserts a word/phrase into box and presses "go".

The word/phrase is than added to multiple URLs on the webpage, replacing some type of token.

When replacing the token, any blank spaces between keywords needs to be replaced with either: + or %20

Example..Page has following URLs:
www.Google.com/search=[keywords]
www.home.com/[keywords].html

Basically, it's really just a simple search/replace function, with the "find" always [keyword] but needs to be broswer based and fill in the blank spaced between keywords.

Thanks in advance...

Steve Diamond 15th September 2009 12:18 PM

Re: Simple javascript needed....
 
Hi, Kurt. Try this:

HTML Code:

<html>
<head>
<script type="text/javascript">
var savedLinks = new Array();

function replaceKW(theStr, theKW) {
        var fixKW = theKW.replace(/ /g,'+');
        var fixStr = theStr.replace('[keywords]',fixKW);
        var fixStr = fixStr.replace('%5Bkeywords%5D',fixKW);
        return fixStr;
}

function doReplace() {
        var theKW = document.getElementById('keywords').value;
        var links = document.getElementsByTagName('a');
        for (var k=0; k<links.length; k++) {
                var theLink = links[k];
                theLink.href = replaceKW(theLink.href, theKW);
                theLink.innerHTML = replaceKW(theLink.innerHTML, theKW);
        }
}

function saveLinks() {
        var links = document.getElementsByTagName('a');
        for (var k=0; k<links.length; k++) {
                var theLink = links[k];
                savedLinks[k] = new Object();
                savedLinks[k]['href'] = theLink.href;
                savedLinks[k]['html'] = theLink.innerHTML;
        }
}

function restoreLinks() {
        var links = document.getElementsByTagName('a');
        for (var k=0; k<links.length; k++) {
                var theLink = links[k];
                theLink.href = savedLinks[k]['href'];
                theLink.innerHTML = savedLinks[k]['html'];
        }
}
</script>

</head>
<body onload="saveLinks();">
        <form onsubmit="return false;">
                Keywords: <input type="text" id="keywords" /> <input type="submit" value="Go" onclick="doReplace();" /><br /><br />
                <input type="submit" value="Restore" onclick="restoreLinks();" />
        </form>
        <a href="http://www.Google.com/search=[keywords]">www.Google.com/search=[keywords]</a><br /><br />
        <a href="http://www.home.com/[keywords].html">www.home.com/[keywords].html</a><br /><br />
        <a href="http://www.home.com/nokeywords.html">www.home.com/nokeywords.html</a>
</body>
</html>

Note that the Restore button will work correctly if and only if no other script has changed any of the links on the page since the time the page was loaded.

HTH.

Steve

Kurt 15th September 2009 04:22 PM

Re: Simple javascript needed....
 
Wow Steve,

Thanks a lot..l.And the reset button was something I didn't think about at all, but now see why it's needed.

Steve Diamond 16th September 2009 09:26 AM

Re: Simple javascript needed....
 
Quote:

Originally Posted by Kurt (Post 1186598)
Wow Steve,

Thanks a lot.

You're very welcome.

Quote:

Originally Posted by Kurt (Post 1186598)
And the reset button was something I didn't think about at all, but now see why it's needed.

Well, that's why I get paid the big bucks :D as a requirements analyst. I'm trained to anticipate unstated requirements before their absence bites anyone in the butt.

Steve

raj564 16th September 2009 10:08 AM

Re: Simple javascript needed....
 
thats a really handy script. thanks!

723Media 16th September 2009 05:33 PM

Re: Simple javascript needed....
 
Hey guys,

I know you needed just a simple script so it may not be an option for you but you could use jQuery and do all of Steve's functionality in about 2 lines.

If you're interested, I can post some sample code.

Steve Diamond 16th September 2009 05:42 PM

Re: Simple javascript needed....
 
I don't know about anyone else, but I for one would be delighted to see how to do this using jQuery. It's one of the next things on my to-learn list.

Thanks.

Steve

723Media 16th September 2009 07:07 PM

Re: Simple javascript needed....
 
Hey Steven,

I put together a quick script. It looks a little intense because of jQuery's awesome chaining abilities but I will break down each part.

BTW, if you like javascript, you will fall in love with jQuery. I am an addict.


Ok, so for this example, I only did the replacement portion to give an idea of how to do this. Here's the code:

The jquery portion:

Code:

<script src="jquery.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $("#btnGo").click(function(e){
               
                e.preventDefault();
               
                $('.keyword').each(function(){
$(this).attr('href', $(this).attr('href').replace('[keywords]','sample')).html($(this).html().replace('[keywords]', 'sample'));
                });
               
            });
        });
    </script>

The HTML portion:

Code:

    <input type="button" id="btnGo" value="Go"/>
Ok, I can't post a link or get it to even represent a link but, the link will have a class="keyword" added to the a tag.

I attached a file with the basic example.

Keeping in mind that the anchor tag has a class of "keyword", let's break this down:

This class of "keyword" is how we will make the anchor tags accessible to jQuery. You could use other methods but that's another story.

So for the jQuery portion.

Lets break it down from start to finish.
Code:

$(document).ready(function(){
This line of code tells jQuery to perform some kind of event or action once the DOM (document) is fully loaded and ready.

Code:

$('#btnGo').click(function(e){
If you notice in the HTML portion, the button has an id of "btnGo". jQuery uses CSS selectors to grab elements in the document. In this case we are saying to jQuery : "Grab the element with the ID (#) of btnGo".

Code:

e.preventDefault();
Since this element is a button, we don't want it's default click event to fire because we want to do some custom event(s). So, this line tells jQuery to prevent the default action.

Now, if you're a nerd like me, is when it gets cool.

Code:

$('.keyword').each(function(){$(this).attr('href',$(this).attr('href').replace('[keywords]','sample')).html($(this).html().replace('[keywords]', 'sample'));
Ok, using the "keyword" class that we gave our links, we tell jQuery to find each one - (".keyword").each and perform a function.

Each is a built loop that will do as it suggests, find each one and perform a custom function.

Code:

$(this).attr('href',$(this).attr('href').replace('[keywords]','sample')).html($(this).html().replace('[keywords]', 'sample'));
In this case, I want to grab each one, read its href attribute and replace the token '[keywords]' with 'sample'. Through the power of chaining, I simply add the fact that I want to also replace the html of the link (it's text value) with the current html, replacing the token with 'sample'.

So, though it was actually more than 2 lines, you can see how jQuery can really reduce code and provide a nice elegant way to do things (once you get the nuances down).

Hope that was fun ;)

Dave

723Media 16th September 2009 07:10 PM

Re: Simple javascript needed....
 
Sorry for taking so long. It took forever getting this post past the regular expressions. I also had some trouble attaching the file. If youre interested in it, PM me.

Steve Diamond 16th September 2009 08:33 PM

Re: Simple javascript needed....
 
Hi, Dave. Thanks for the jQuery tutorial! Very interesting. Looks like powerful stuff, but the syntax isn't exactly intuitive, is it? I'll have to do some tinkering to get comfortable.

I'll PM you my email so you can send the file.

Steve


All times are GMT -6. The time now is 08:30 PM.