Simple javascript needed....

by Kurt
9 replies
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...
#javascript #needed #simple
  • Profile picture of the author Steve Diamond
    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
    Signature
    Mindfulness training & coaching online
    Reduce stress | Stay focused | Keep positive and balanced
    {{ DiscussionBoard.errors[1185875].message }}
  • Profile picture of the author raj564
    thats a really handy script. thanks!
    {{ DiscussionBoard.errors[1188966].message }}
  • Profile picture of the author 723Media
    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.
    {{ DiscussionBoard.errors[1190147].message }}
    • Profile picture of the author Steve Diamond
      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
      Signature
      Mindfulness training & coaching online
      Reduce stress | Stay focused | Keep positive and balanced
      {{ DiscussionBoard.errors[1190172].message }}
  • Profile picture of the author 723Media
    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
    {{ DiscussionBoard.errors[1190352].message }}
  • Profile picture of the author 723Media
    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.
    {{ DiscussionBoard.errors[1190363].message }}
    • Profile picture of the author Steve Diamond
      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
      Signature
      Mindfulness training & coaching online
      Reduce stress | Stay focused | Keep positive and balanced
      {{ DiscussionBoard.errors[1190512].message }}

Trending Topics