Google Answers Logo
View Question
 
Q: Javascript - Swap one word for another. ( Answered 5 out of 5 stars,   1 Comment )
Question  
Subject: Javascript - Swap one word for another.
Category: Computers > Programming
Asked by: flutter-ga
List Price: $80.00
Posted: 17 Dec 2004 15:08 PST
Expires: 16 Jan 2005 15:08 PST
Question ID: 444123
I have a poem which includes someone's name. I want visitors to my
site to be able to view the poem with their own name in it.

Can someone take the code below and:

1. Add a simple form (input text box and button)

2. Insert javascript so when the button is pressed the word 'visitor'
changes to whatever is entered into the text field.
When you enter a new name and click the button again the new name appears where
'visitor' once was.

(if there is a name in the text box when the button is clicked the
name will appear in the poem - if the text box is empty, 'visitor'
appears. When the page loads 'visitor' should be there)

Thanks.

<html>
<head>
<title>NameSwap</title>
</head>
<body>
<table>
<tr>
<td>
Visitor went for a walk at eight o'clock<br>
Carrying a length of chain and lock<br>
Visitor was shaking
</td>
</tr>
<tr>
<td>
Visitor was quaking<br>
Visitor was wearing just one sock
</td>
</tr>
</table>
Visitor went exploring with a friend<br>
And wished that sunny days would never end<br>
Then visitor saw Willow<br>
Dancing with a pillow<br>
Willow said &quot;Visitor can pretend&quot;
</body>
</html>
Answer  
Subject: Re: Javascript - Swap one word for another.
Answered By: leapinglizard-ga on 18 Dec 2004 21:18 PST
Rated:5 out of 5 stars
 
Dear flutter,

Although JavaScript cannot modify the contents of a page once it has
been loaded, the functionality you specified can be achieved by
loading a new page with different content.

When the HTML code below is first loaded, the print_poem() function
tries to parse the URL so that the query portion can be used as a
name. If no query is found, the function replaces all occurrences of
"NAME" in the poem text with the value of the variable default_name,
currently set to "<em>Visitor</em>". Feel free to modify default_name
to your liking. Note also my assumption that your page does not
already use a query. If this assumption is false, please let me know
so that I can work around it with more sophisticated string
extraction.

The enter() function is triggered when the user clicks on the form
button, currently labeled "Enter". It takes the content of the text
field and attaches it to the non-query portion of the current URL to
form a new URL, which it then loads. As a result, the print_poem()
function will find a new query value to substitute for "NAME" in the
poem.

HTML code follows.


<html>
  <head>
    <title> NameSwap </title>

    <script type="text/javascript">

        function print_poem() {
            var default_name = "<em>Visitor</em>";
            var name = location.search.slice(1, location.search.length);
            if (name.length == 0) {
                name = default_name;
            }
            name = name.replace(/%20/g, " ");
            var poem_text = ""+
              "<table>"+
                "<tr><td>"+
                  "NAME went for a walk at eight o'clock <br>"+
                  "Carrying a length of chain and lock <br>"+
                  "NAME was shaking"+
                "</td></tr>"+
                "<tr><td>"+
                  "NAME was quaking <br>"+
                  "NAME was wearing just one sock"+
                "</td></tr>"+
                "<tr><td>"+
                  "NAME went exploring with a friend <br>"+
                  "And wished that sunny days would never end <br>"+
                  "Then NAME saw Willow<br>"+
                  "Dancing with a pillow<br>"+
                  "Willow said &quot;NAME can pretend&quot;"+
                "</td></tr>"+
              "</table>"+
            "";
            poem_text = poem_text.replace(/NAME/g, name);
            document.write(poem_text);
        }

        function enter() {
            var name = document.name_form.name_text.value;
            document.name_form.reset();
            var path = location.pathname;
            location.replace(path+"?"+name);
        }

    </script>

  </head>
  <body>

    <form name="name_form" action="" onSubmit="enter(); return false">
      <em> your name: </em>
      <input type="text" name="name_text" />
      <input type="button" value="Enter" onClick="enter()" />
    </form>

    <script type="text/javascript">
        print_poem();
    </script>

  </body>
</html>


You can try out this code immediately at the following address.

http://plg.uwaterloo.ca/~mlaszlo/answers/nameswap.html

It should work exactly the same way on your webhost, unless there is
query interference such as I described earlier. Also, the string
replacement methods are not recognized by very old versions of
JavaScript that are essentially extinct. If this should prove to be a
problem, I can always change the print_poem() code to something more
primitive that will do the same job, but at the expense of
readability. In its present form, you should find it fairly easy to
modify the poem text without breaking the JavaScript.

Should you have any trouble with this code, please let me know through
a Clarification Request so that I can attend to your needs before you
assign a rating. Although I cannot add new functionality within the
scope of the present question, I will take all steps to ensure that
this web page meets the specifications you gave above.

Regards,

leapinglizard
flutter-ga rated this answer:5 out of 5 stars
Thankyou leapinglizard-ga. This code does exactly what I needed. I was
banging my head against a brickwall and you helped to stop. I
appreciate your help.

Comments  
Subject: Re: Javascript - Swap one word for another.
From: lesnikowski-ga on 20 Dec 2004 14:03 PST
 
It works in IE 6.0 and FireFox 1.0:
<html>
<head>
<title>NameSwap</title>
<script>
var text=null;
function Change()
{
	newName=document.getElementById("visitor").value.toLowerCase();
	if (newName=="")
		newName="visitor";
	newUpperName=newName.charAt(0).toUpperCase()+newName.substr(1);
	
	p=document.getElementById("poem");
	if (text==null)
		text=p.innerHTML;
	tmp=text.replace(/visitor/g,newName);
	p.innerHTML=tmp.replace(/Visitor/g,newUpperName);
}
</script>

</head>
<body>

<input type="text" value="visitor" ID="visitor" NAME="visitor"></input>
<input type="button" onclick="Change()" value="Change"></input>

<div id="poem">
Visitor went for a walk at eight o'clock<br>
Carrying a length of chain and lock<br>
Visitor was shaking
Visitor was quaking<br>
Visitor was wearing just one sock
Visitor went exploring with a friend<br>
And wished that sunny days would never end<br>
Then visitor saw Willow<br>
Dancing with a pillow<br>
Willow said &quot;Visitor can pretend&quot;
</div>

</body>
</html>

Important Disclaimer: Answers and comments provided on Google Answers are general information, and are not intended to substitute for informed professional medical, psychiatric, psychological, tax, legal, investment, accounting, or other professional advice. Google does not endorse, and expressly disclaims liability for any product, manufacturer, distributor, service or service provider mentioned or any opinion expressed in answers or comments. Please read carefully the Google Answers Terms of Service.

If you feel that you have found inappropriate content, please let us know by emailing us at answers-support@google.com with the question ID listed above. Thank you.
Search Google Answers for
Google Answers  


Google Home - Answers FAQ - Terms of Service - Privacy Policy