<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Random Snippets &#187; onclick event</title>
	<atom:link href="http://www.randomsnippets.com/tag/onclick-event/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.randomsnippets.com</link>
	<description>Random Snippets of Code and Ideas for any Web Developer</description>
	<lastBuildDate>Wed, 05 Aug 2009 14:32:02 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=abc</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>How to find and access parent nodes via JavaScript</title>
		<link>http://www.randomsnippets.com/2008/06/26/how-to-find-and-access-parent-nodes-via-javascript/</link>
		<comments>http://www.randomsnippets.com/2008/06/26/how-to-find-and-access-parent-nodes-via-javascript/#comments</comments>
		<pubDate>Fri, 27 Jun 2008 06:15:53 +0000</pubDate>
		<dc:creator>Knix</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[dom tree]]></category>
		<category><![CDATA[findParentNode]]></category>
		<category><![CDATA[onClick]]></category>
		<category><![CDATA[onclick event]]></category>
		<category><![CDATA[parent node]]></category>
		<category><![CDATA[parent nodes]]></category>
		<category><![CDATA[parentName]]></category>
		<category><![CDATA[parentNode]]></category>
		<category><![CDATA[tagName]]></category>

		<guid isPermaLink="false">http://www.randomsnippets.com/?p=19</guid>
		<description><![CDATA[
function findParentNode(parentName, childObj) {
    var testObj = childObj.parentNode;
    var count = 1;
    while(testObj.getAttribute('name') != parentName) {
        alert('My name is ' + testObj.getAttribute('name') + '. Let\'s try moving up one level to see what we get.');
     [...]]]></description>
			<content:encoded><![CDATA[<p><script language="javascript">
function findParentNode(parentName, childObj) {
    var testObj = childObj.parentNode;
    var count = 1;
    while(testObj.getAttribute('name') != parentName) {
        alert('My name is ' + testObj.getAttribute('name') + '. Let\'s try moving up one level to see what we get.');
        testObj = testObj.parentNode;
        count++;
    }
    // now you have the object you are looking for - do something with it
    alert('Finally found ' + testObj.getAttribute('name') + ' after going up ' + count + ' level(s) through the DOM tree');
}
</script><br />
Have you ever had to access a parent node from a given child node?  In this example, we are going to traverse up the DOM tree starting from the button to look for the parent node with the <b>name</b> attribute <b>itsMe</b>.</p>
<fieldset>
<legend>Demo</legend>
<div name="notMe" style="padding:10px;border:1px solid green;">
My name is <b>notMe</b></p>
<div name="itsMe" style="padding:10px;border:1px solid blue;">
    My name is <b>itsMe</b></p>
<div name="notMeEither" style="padding:10px;border:1px solid red;">
        My name is <b>notMeEither</b></p>
<div name="tryAgain" style="padding:10px;border:1px solid purple;">
            My name is <b>tryAgain</b></p>
<div name="sorryNotMe" style="padding:10px;border:1px solid black;">
                My name is <b>sorryNotMe</b></p>
<div name="nopeSorry" style="padding:10px;border:1px solid brown;">
                    My name is <b>nopeSorry</b></p>
<input type="button" value="Find Parent Object with name=itsMe" onClick="findParentNode('itsMe', this);">
                    </div>
</p></div>
</p></div>
</p></div>
</p></div>
</div>
</fieldset>
<p><span id="more-19"></span><br />
Here is the HTML code.  It&#8217;s just a series of embedded div elements with different names and the input button where we start to traverse up the DOM tree accessing each parent node and asking for it&#8217;s name attribute value. The <b>onClick</b> event of the button triggers the <b>findParentNode</b> and passes the name of the element we are looking for and the object itself which, in this case, is the button.  This is the starting point where we will begin traversing up the DOM tree by accessing the parent nodes of each element and seeing if the name attribute matches what we are looking for.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">&lt;div name=&quot;notMe&quot; style=&quot;padding:10px;border:1px solid green;&quot;&gt;
My name is &lt;b&gt;notMe&lt;/b&gt;
    &lt;div name=&quot;itsMe&quot; style=&quot;padding:10px;border:1px solid blue;&quot;&gt;
    My name is &lt;b&gt;itsMe&lt;/b&gt;
        &lt;div name=&quot;notMeEither&quot; style=&quot;padding:10px;border:1px solid red;&quot;&gt;
        My name is &lt;b&gt;notMeEither&lt;/b&gt;
            &lt;div name=&quot;tryAgain&quot; style=&quot;padding:10px;border:1px solid purple;&quot;&gt;
            My name is &lt;b&gt;tryAgain&lt;/b&gt;
                &lt;div name=&quot;sorryNotMe&quot; style=&quot;padding:10px;border:1px solid black;&quot;&gt;
                My name is &lt;b&gt;sorryNotMe&lt;/b&gt;
                    &lt;div name=&quot;nopeSorry&quot; style=&quot;padding:10px;border:1px solid brown;&quot;&gt;
                    My name is &lt;b&gt;nopeSorry&lt;/b&gt;
                        &lt;input type=&quot;button&quot; value=&quot;Find Parent Object with name=itsMe&quot; onClick=&quot;findParentNode('itsMe', this);&quot;&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;</pre></td></tr></table></div>

<p>Here is the <b>findParentNode</b> JavaScript code:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="javascript javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> findParentNode<span style="color: #009900;">&#40;</span>parentName<span style="color: #339933;">,</span> childObj<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> testObj <span style="color: #339933;">=</span> childObj.<span style="color: #660066;">parentNode</span>;
    <span style="color: #003366; font-weight: bold;">var</span> count <span style="color: #339933;">=</span> <span style="color: #CC0000;">1</span>;
    <span style="color: #000066; font-weight: bold;">while</span><span style="color: #009900;">&#40;</span>testObj.<span style="color: #660066;">getAttribute</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'name'</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">!=</span> parentName<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'My name is '</span> <span style="color: #339933;">+</span> testObj.<span style="color: #660066;">getAttribute</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'name'</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">'. Let<span style="color: #000099; font-weight: bold;">\'</span>s try moving up one level to see what we get.'</span><span style="color: #009900;">&#41;</span>;
        testObj <span style="color: #339933;">=</span> testObj.<span style="color: #660066;">parentNode</span>;
        count++;
    <span style="color: #009900;">&#125;</span>
    <span style="color: #006600; font-style: italic;">// now you have the object you are looking for - do something with it</span>
    <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'Finally found '</span> <span style="color: #339933;">+</span> testObj.<span style="color: #660066;">getAttribute</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'name'</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">' after going up '</span> <span style="color: #339933;">+</span> count <span style="color: #339933;">+</span> <span style="color: #3366CC;">' level(s) through the DOM tree'</span><span style="color: #009900;">&#41;</span>;
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>In line 2, we access the parent node of the child element via the <b>parentNode</b> method which is the first div above the button named <b>nopeSorry</b>.  We then begin a count of the number of times we traversed up the DOM tree and set it to 1 because we have already accessed the parent node once.  The while loop will test if the name of the current node will match the name that we are looking for.  If not, it moves up the DOM tree by accessing the next parent node and continues to look for the right name while increasing the count by 1 each time.  Once it finds the right node, the function exits the while loop and alerts the node name along with the number of times it traversed up the DOM tree.</p>
<p>If you do not know the name of the parent element you are looking for you can also search using the <b>tagName</b> method.  The tagName will return the value of the tag name of the given node such as <b>A</b> or <b>DIV</b>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.randomsnippets.com/2008/06/26/how-to-find-and-access-parent-nodes-via-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to create your own customized calculator via JavaScript</title>
		<link>http://www.randomsnippets.com/2008/04/26/how-to-create-your-own-customized-calculator-via-javascript/</link>
		<comments>http://www.randomsnippets.com/2008/04/26/how-to-create-your-own-customized-calculator-via-javascript/#comments</comments>
		<pubDate>Sun, 27 Apr 2008 01:01:51 +0000</pubDate>
		<dc:creator>Knix</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[addition and subtraction]]></category>
		<category><![CDATA[calculator]]></category>
		<category><![CDATA[dynamic]]></category>
		<category><![CDATA[input buttons]]></category>
		<category><![CDATA[input object]]></category>
		<category><![CDATA[javascript code]]></category>
		<category><![CDATA[multiplication]]></category>
		<category><![CDATA[onclick event]]></category>

		<guid isPermaLink="false">http://www.randomsnippets.com/?p=15</guid>
		<description><![CDATA[
function calculate(equation) {
     var answer = eval(equation);
     document.getElementById('screen').value = answer;
}
function pushButton(buttonValue) {
     if (buttonValue == 'C') {
          document.getElementById('screen').value = '';
     }
     else {
    [...]]]></description>
			<content:encoded><![CDATA[<p><script lang="javascript">
function calculate(equation) {
     var answer = eval(equation);
     document.getElementById('screen').value = answer;
}
function pushButton(buttonValue) {
     if (buttonValue == 'C') {
          document.getElementById('screen').value = '';
     }
     else {
          document.getElementById('screen').value += buttonValue;
     }
}
</script></p>
<style type="text/css">
table.calc {
     border: 2px solid #0034D1;
     background-color: #809FFF;
}
input.calc {
     width: 100%;
     margin: 5px;
}
tr.calc {
     border: 0px;
}
</style>
<p>This is a simple example of implementing a calculator with JavaScript and HTML.  This calculator will only have the division, multiplication, addition, and subtraction operators but you can easily tack on more functions if needed.</p>
<fieldset>
<legend>Demo</legend>
<table class="calc" cellpadding=4>
<tr class="calc">
<td colspan=3>
<input class="calc" id="screen" type="text"></td>
</tr>
<tr class="calc">
<td>
<input class="calc" type="button" value=1 onclick="pushButton(this.value);"></td>
<td>
<input class="calc" type="button" value=2 onclick="pushButton(this.value);"></td>
<td>
<input class="calc" type="button" value=3 onclick="pushButton(this.value);"></td>
<td>
<input class="calc" type="button" value='/' onclick="pushButton(this.value);"></td>
</tr>
<tr>
<td>
<input class="calc" type="button" value=4 onclick="pushButton(this.value);"></td>
<td>
<input class="calc" type="button" value=5 onclick="pushButton(this.value);"></td>
<td>
<input class="calc" type="button" value=6 onclick="pushButton(this.value);"></td>
<td>
<input class="calc" type="button" value='*' onclick="pushButton(this.value);"></td>
</tr>
<tr>
<td>
<input class="calc" type="button" value=7 onclick="pushButton(this.value);"></td>
<td>
<input class="calc" type="button" value=8 onclick="pushButton(this.value);"></td>
<td>
<input class="calc" type="button" value=9 onclick="pushButton(this.value);"></td>
<td>
<input class="calc" type="button" value='-' onclick="pushButton(this.value);"></td>
</tr>
<tr>
<td>
<input class="calc" type="button" value=0 onclick="pushButton(this.value);"></td>
<td>
<input class="calc" type="button" value='.' onclick="pushButton(this.value);"></td>
<td>
<input class="calc" type="button" value='C' onclick="pushButton(this.value);"></td>
<td>
<input class="calc" type="button" value='+' onclick="pushButton(this.value);"></td>
</tr>
<tr>
<td colspan=3>
<input class="calc" type="button" value='=' onclick="calculate(document.getElementById('screen').value);"></td>
</tr>
</table>
</fieldset>
<p><span id="more-15"></span><br />
Here is the html code including the CSS stuff:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">&lt;style type=&quot;text/css&quot;&gt;
table.calc {
     border: 2px solid #0034D1;
     background-color: #809FFF;
}
input.calc {
     width: 100%;
     margin: 5px;
}
&lt;/style&gt;
&lt;fieldset&gt;
&lt;legend&gt;Demo&lt;/legend&gt;
&lt;table class=&quot;calc&quot; cellpadding=4&gt;
&lt;tr&gt;&lt;td colspan=3&gt;&lt;input class=&quot;calc&quot; id=&quot;screen&quot; type=&quot;text&quot;&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;input class=&quot;calc&quot; type=&quot;button&quot; value=1 onclick=&quot;pushButton(this.value);&quot;&gt;&lt;/td&gt;
&lt;td&gt;&lt;input class=&quot;calc&quot; type=&quot;button&quot; value=2 onclick=&quot;pushButton(this.value);&quot;&gt;&lt;/td&gt;
&lt;td&gt;&lt;input class=&quot;calc&quot; type=&quot;button&quot; value=3 onclick=&quot;pushButton(this.value);&quot;&gt;&lt;/td&gt;
&lt;td&gt;&lt;input class=&quot;calc&quot; type=&quot;button&quot; value='/' onclick=&quot;pushButton(this.value);&quot;&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;input class=&quot;calc&quot; type=&quot;button&quot; value=4 onclick=&quot;pushButton(this.value);&quot;&gt;&lt;/td&gt;
&lt;td&gt;&lt;input class=&quot;calc&quot; type=&quot;button&quot; value=5 onclick=&quot;pushButton(this.value);&quot;&gt;&lt;/td&gt;
&lt;td&gt;&lt;input class=&quot;calc&quot; type=&quot;button&quot; value=6 onclick=&quot;pushButton(this.value);&quot;&gt;&lt;/td&gt;
&lt;td&gt;&lt;input class=&quot;calc&quot; type=&quot;button&quot; value='*' onclick=&quot;pushButton(this.value);&quot;&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;input class=&quot;calc&quot; type=&quot;button&quot; value=7 onclick=&quot;pushButton(this.value);&quot;&gt;&lt;/td&gt;
&lt;td&gt;&lt;input class=&quot;calc&quot; type=&quot;button&quot; value=8 onclick=&quot;pushButton(this.value);&quot;&gt;&lt;/td&gt;
&lt;td&gt;&lt;input class=&quot;calc&quot; type=&quot;button&quot; value=9 onclick=&quot;pushButton(this.value);&quot;&gt;&lt;/td&gt;
&lt;td&gt;&lt;input class=&quot;calc&quot; type=&quot;button&quot; value='-' onclick=&quot;pushButton(this.value);&quot;&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;input class=&quot;calc&quot; type=&quot;button&quot; value=0 onclick=&quot;pushButton(this.value);&quot;&gt;&lt;/td&gt;
&lt;td&gt;&lt;input class=&quot;calc&quot; type=&quot;button&quot; value='.' onclick=&quot;pushButton(this.value);&quot;&gt;&lt;/td&gt;
&lt;td&gt;&lt;input class=&quot;calc&quot; type=&quot;button&quot; value='C' onclick=&quot;pushButton(this.value);&quot;&gt;&lt;/td&gt;
&lt;td&gt;&lt;input class=&quot;calc&quot; type=&quot;button&quot; value='+' onclick=&quot;pushButton(this.value);&quot;&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;&lt;td colspan=3&gt;&lt;input class=&quot;calc&quot; type=&quot;button&quot; value='=' onclick=&quot;calculate(document.getElementById('screen').value);&quot;&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;</pre></td></tr></table></div>

<p>Most of the HTML is coding for all the input buttons and their associated <b>onclick</b> event handlers.  All the buttons, except for the <b>=</b> button, will call the <b>pushButton</b> JavaScript when clicked and passes it&#8217;s associated value.  The <b>=</b> button calls the <b>calculate</b> JavaScript function and passes the value that is in the text input which represents the string of numbers and operators that were pushed.  The rest of the HTML is just icing on the cake so that it actually looks like a calculator.</p>
<p>Here is the JavaScript code for the 2 functions:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="javascript javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> pushButton<span style="color: #009900;">&#40;</span>buttonValue<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
     <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>buttonValue <span style="color: #339933;">==</span> <span style="color: #3366CC;">'C'</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
          document.<span style="color: #660066;">getElementById</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'screen'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">value</span> <span style="color: #339933;">=</span> <span style="color: #3366CC;">''</span>;
     <span style="color: #009900;">&#125;</span>
     <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
          document.<span style="color: #660066;">getElementById</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'screen'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">value</span> <span style="color: #339933;">+=</span> buttonValue;
     <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #003366; font-weight: bold;">function</span> calculate<span style="color: #009900;">&#40;</span>equation<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
     <span style="color: #003366; font-weight: bold;">var</span> answer <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">eval</span><span style="color: #009900;">&#40;</span>equation<span style="color: #009900;">&#41;</span>;
     document.<span style="color: #660066;">getElementById</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'screen'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">value</span> <span style="color: #339933;">=</span> answer;
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>The <b>pushButton</b> function does 2 things for us.  If the user clicks on the <b>C</b> button or the clear button, it accesses the text input object, which represents our calculator screen, via the DOM .  Once it is accessed, the value inside the text input is set to &#8221; (2 single quotes) which is an empty string.  This will basically remove whatever string is already inside the text input.  If the user clicks on any other button, the function will access the text input object and append the value that was passed over to whatever is already in our text input.  This allows us to build our string with numbers and operators.</p>
<p>The <b>calculate</b> function does exactly what it&#8217;s name suggests.  It takes our string of numbers and operators and evaluates it in line 10.  The <b>eval()</b> function treats the string as if it were JavaScript code and executes it and returns the results.  The function will then access the text input object and replace whatever the current value is with the answer from the <b>eval()</b> function.</p>
<p>That&#8217;s it!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.randomsnippets.com/2008/04/26/how-to-create-your-own-customized-calculator-via-javascript/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>How to validate email format via JavaScript</title>
		<link>http://www.randomsnippets.com/2008/04/01/how-to-verify-email-format-via-javascript/</link>
		<comments>http://www.randomsnippets.com/2008/04/01/how-to-verify-email-format-via-javascript/#comments</comments>
		<pubDate>Wed, 02 Apr 2008 05:30:08 +0000</pubDate>
		<dc:creator>Knix</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[checkEmail]]></category>
		<category><![CDATA[emailRegEx]]></category>
		<category><![CDATA[form]]></category>
		<category><![CDATA[javascript demo]]></category>
		<category><![CDATA[javascript email]]></category>
		<category><![CDATA[javascript function]]></category>
		<category><![CDATA[onclick event]]></category>
		<category><![CDATA[regex]]></category>
		<category><![CDATA[valid email address]]></category>
		<category><![CDATA[verification]]></category>
		<category><![CDATA[verifyEmail]]></category>

		<guid isPermaLink="false">http://www.randomsnippets.com/?p=13</guid>
		<description><![CDATA[
This JavaScript demo verifies that an email address is in the correct format and that the user has typed in the same address in both fields to prevent mistyping of the address.  I have borrowed the regex for verifying the correct email format from a different site. 

Demo

Email:



Please type in your email again:






Here is [...]]]></description>
			<content:encoded><![CDATA[<p><script src="/wp-includes/js/verifyEmail.js" language="Javascript" type="text/javascript"></script><br />
This JavaScript demo verifies that an email address is in the correct format and that the user has typed in the same address in both fields to prevent mistyping of the address.  I have <a href="http://www.regular-expressions.info/email.html" target="_blank">borrowed the regex for verifying the correct email format</a> from a different site. </p>
<fieldset>
<legend>Demo</legend>
<form name="myform">
Email:<br />
<input type="text" name="email1">
<p>
<p>
Please type in your email again:<br />
<input type="text" name="email2">
<p>
<input type="button" onclick="verifyEmail();" value="Check Email Address">
</form>
</fieldset>
<p><span id="more-13"></span><br />
Here is the plain HTML of the form.  Please note that I have removed the action attribute because this is only a demo and we are only concerned with the client-side verification of the JavaScript function.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">&lt;form name=&quot;myform&quot;&gt;
Email: &lt;input type=&quot;text&quot; name=&quot;email1&quot;&gt;
&lt;p&gt;&lt;p&gt;
Please type in your email again: &lt;input type=&quot;text&quot; name=&quot;email2&quot;&gt;
&lt;p&gt;&lt;p&gt;
&lt;input type=&quot;button&quot; onClick=&quot;verifyEmail();&quot; value=&quot;Check Email Address&quot;&gt;
&lt;/form&gt;</pre></td></tr></table></div>

<p>Nothing exciting here except in line 6 where the <b>onClick</b> event is triggered when the user clicks on the button.  This event will launch the <b>verifyEmail()</b> JavaScript function which will check the user input of the email address.</p>
<p>Here is the code for the <b>verifyEmail()</b> function:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
</pre></td><td class="code"><pre class="javascript javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> verifyEmail<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
<span style="color: #003366; font-weight: bold;">var</span> <span style="color: #000066;">status</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">false</span>;     
<span style="color: #003366; font-weight: bold;">var</span> emailRegEx <span style="color: #339933;">=</span> <span style="color: #009966; font-style: italic;">/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i</span>;
     <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>document.<span style="color: #660066;">myform</span>.<span style="color: #660066;">email1</span>.<span style="color: #660066;">value</span>.<span style="color: #660066;">search</span><span style="color: #009900;">&#40;</span>emailRegEx<span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #339933;">-</span><span style="color: #CC0000;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
          <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Please enter a valid email address.&quot;</span><span style="color: #009900;">&#41;</span>;
     <span style="color: #009900;">&#125;</span>
     <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>document.<span style="color: #660066;">myform</span>.<span style="color: #660066;">email1</span>.<span style="color: #660066;">value</span> <span style="color: #339933;">!=</span> document.<span style="color: #660066;">myform</span>.<span style="color: #660066;">email2</span>.<span style="color: #660066;">value</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
          <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Email addresses do not match.  Please retype them to make sure they are the same.&quot;</span><span style="color: #009900;">&#41;</span>;
     <span style="color: #009900;">&#125;</span>
     <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
          <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Woohoo!  The email address is in the correct format and they are the same.&quot;</span><span style="color: #009900;">&#41;</span>;
          <span style="color: #000066;">status</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">true</span>;
     <span style="color: #009900;">&#125;</span>
     <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #000066;">status</span>;
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>This function will return a <b>false</b> value if the user does not type in an email address in the correct format or if the user fails to type in the same email address in both fields.  If the email addresses passes both these tests, then the function will return a <b>true</b> value.</p>
<p>The <a href="http://www.regular-expressions.info/email.html" target="_blank">regex for validating the correct email format in line 2 has been borrowed</a> and edited slightly by adding the <b>i</b> flag so that the regex is case-insensitive.</p>
<p>The <b>if</b> block in lines 3-6 checks to see if the email address in the first field passes the regex check by invoking the <b>search()</b> method on our email string value.  This method accepts regex expressions as arguments to check the string and returns the position of the specified value in the string or a <b>-1</b> if no match was found.  If the <b>search()</b> method returns a <b>-1</b>, then an alert would tell the user that an invalid email address has been entered and returns a <b>false</b> value.</p>
<p>Lines 7-10 checks to see if the user has entered the same string in both email fields.  This is done by a simple equality check on the string values.  If the strings are different, an alert warns the user that the email addresses are not the same and returns a <b>false</b> value.</p>
<p>If we have passed the two tests, then <b>else</b> block in lines 11-14 gets executed.  An alert tells the user that he or she has done a good job and the function returns a <b>true</b> value so that you  can continue with the form submission.</p>
<p>Ideally, you would have this function run during the <b>onSubmit</b> attribute for the <b>form</b> tag.  This way, the form will get submitted when the <b>checkEmail()</b> function returns a <b>true</b> value.  Here is an example of how your form would look like:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">&lt;form name=&quot;myForm&quot; method=&quot;POST&quot; action=&quot;myTargetFile&quot; onSubmit=&quot;return checkEmail()&quot;&gt;
Email: &lt;input type=&quot;text&quot; name=&quot;email1&quot;&gt;
&lt;p&gt;&lt;p&gt;
Please type in your email again: &lt;input type=&quot;text&quot; name=&quot;email2&quot;&gt;
&lt;p&gt;&lt;p&gt;
&lt;input type=&quot;submit&quot; value=&quot;Submit&quot;&gt;
&lt;/form&gt;</pre></td></tr></table></div>

]]></content:encoded>
			<wfw:commentRss>http://www.randomsnippets.com/2008/04/01/how-to-verify-email-format-via-javascript/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>How to dynamically remove/delete elements via JavaScript</title>
		<link>http://www.randomsnippets.com/2008/03/26/how-to-dynamically-removedelete-elements-via-javascript/</link>
		<comments>http://www.randomsnippets.com/2008/03/26/how-to-dynamically-removedelete-elements-via-javascript/#comments</comments>
		<pubDate>Thu, 27 Mar 2008 05:57:53 +0000</pubDate>
		<dc:creator>Knix</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[dynamic]]></category>
		<category><![CDATA[getElementById]]></category>
		<category><![CDATA[onclick event]]></category>
		<category><![CDATA[remove]]></category>
		<category><![CDATA[removeChild]]></category>
		<category><![CDATA[removeElement]]></category>

		<guid isPermaLink="false">http://www.randomsnippets.com/2008/03/26/how-to-dynamically-removedelete-elements-via-javascript/</guid>
		<description><![CDATA[
function removeElement(parentDiv, childDiv){
     if (childDiv == parentDiv) {
          alert("The parent div cannot be removed.");
     }
     else if (document.getElementById(childDiv)) {     
          var [...]]]></description>
			<content:encoded><![CDATA[<p><script lang="javascript">
function removeElement(parentDiv, childDiv){
     if (childDiv == parentDiv) {
          alert("The parent div cannot be removed.");
     }
     else if (document.getElementById(childDiv)) {     
          var child = document.getElementById(childDiv);
          var parent = document.getElementById(parentDiv);
          parent.removeChild(child);
     }
     else {
          alert("Child div has already been removed or does not exist.");
          return false;
     }
}
</script><br />
This post is in response to one of the <a href="/2008/02/21/how-to-dynamically-add-form-elements-via-javascript/#comment-10">comments on have received regarding the removal of elements via JavaScript</a>.  I have taken the original function posted and edited it a little bit for the demo.</p>
<fieldset>
<legend>Demo</legend>
<div id="parent" style="border: 1px solid red; padding: 10px;">
     I am the parent div.</p>
<div id="child" style="border: 1px solid green; padding: 10px;">
          I am a child div within the parent div.
     </div>
</div>
<p>&nbsp;</p>
<input type="button" value="Remove Element" onClick="removeElement('parent','child');">
</fieldset>
<p><span id="more-12"></span><br />
Here is the plain HTML code:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">&lt;div id=&quot;parent&quot; style=&quot;border: 1px solid red; padding: 10px;&quot;&gt;
     I am the parent div.
     &lt;div id=&quot;child&quot; style=&quot;border: 1px solid green; padding: 10px;&quot;&gt;
           I am a child div within the parent div.
     &lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;input type=&quot;button&quot; value=&quot;Remove Element&quot; onClick=&quot;removeElement('parent','child');&quot;&gt;</pre></td></tr></table></div>

<p>The important thing to note here is that the <b>child div</b> is <b>within</b> the <b>parent div</b>.  Once the <b>Remove Element</b> button is clicked, the <b>onClick</b> event listener is triggered and launches the <b>removeElement</b> JavaScript function.  This functions accepts two arguments:</p>
<ul>
<li><b>parent</b> &#8211; This is just the <b>div id</b> of the parent div.</li>
<li><b>child</b> &#8211; This is the <b>div id</b> of the child div.</li>
</ul>
<p>Here is the code for the <b>removeElement</b> JavaScript function:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">function removeElement(parentDiv, childDiv){
     if (childDiv == parentDiv) {
          alert(&quot;The parent div cannot be removed.&quot;);
     }
     else if (document.getElementById(childDiv)) {     
          var child = document.getElementById(childDiv);
          var parent = document.getElementById(parentDiv);
          parent.removeChild(child);
     }
     else {
          alert(&quot;Child div has already been removed or does not exist.&quot;);
          return false;
     }
}</pre></td></tr></table></div>

<p>The <b>if</b> block in lines 2-6 attempts to obtain the <b>child</b> element if it exists.  This is just in case the user has already removed the child div and is reattempting to it.  In this case, a JavaScript error would normally pop up because the child div does not exist.  </p>
<p>If the child element does exist, the first thing that we do is obtain the <b>child</b> element in line 3 using the <b>child div id</b>.  Next, we do the same thing with the <b>parent</b> element by using the <b>parent div id</b>  Lastly, we invoke the <b>removeChild</b> method from the parent element and pass the child element as the argument.  That&#8217;s it!</p>
<p>If the child div has already been removed, the <b>else</b> block in lines 7-10 gets executed.  In this case, an alert would tell the user that the child div has already been removed and the function would return a <b>false</b> value.</p>
<p>Here is another demo of this JavaScript function where you can type in the name of the child element to be removed and just click on the <b>Remove Element</b> button <b>OR</b> you can just click the button that corresponds to each given child div to remove it.</p>
<fieldset>
<legend>Demo</legend>
<div id="parentDiv" style="border: 1px solid red; padding: 10px;">
     My name is <b>parentDiv</b>.  I cannot be removed.</p>
<div id="child1" style="border: 1px solid green; padding: 10px; margin: 10px;">
          My name is <b>child1</b>.
     </div>
<div id="child2" style="border: 1px solid blue; padding: 10px; margin: 10px;">
          My name is <b>child2</b>.
     </div>
<div id="child3" style="border: 1px solid purple; padding: 10px; margin: 10px;">
          My name is <b>child3</b>.
     </div>
</div>
<p>&nbsp;</p>
<p>Name of child element to be removed:<br />
<input id="nameOfChild" type="text" value="child2">
<input type="button" value="Remove Element" onClick="var name=document.getElementById('nameOfChild').value; removeElement('parentDiv', name);">
<p>For those who are lazy in typing in the actual names, we have these handy-dandy buttons:</p>
<input type="button" value="Remove child1" onClick="removeElement('parentDiv', 'child1');">
<input type="button" value="Remove child2" onClick="removeElement('parentDiv', 'child2');">
<input type="button" value="Remove child3" onClick="removeElement('parentDiv', 'child3');">
<input type="button" value="Remove parentDiv" onClick="removeElement('parentDiv', 'parentDiv');">
</fieldset>
<p>We are using the same JavaScript function as above.  Here is the plain HTML for the demo:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">&lt;div id=&quot;parentDiv&quot; style=&quot;border: 1px solid red; padding: 10px;&quot;&gt;
     My name is &lt;b&gt;parentDiv&lt;/b&gt;.  I cannot be removed.
     &lt;div id=&quot;child1&quot; style=&quot;border: 1px solid green; padding: 10px; margin: 10px;&quot;&gt;
          My name is &lt;b&gt;child1&lt;/b&gt;.
     &lt;/div&gt;
     &lt;div id=&quot;child2&quot; style=&quot;border: 1px solid blue; padding: 10px; margin: 10px;&quot;&gt;
          My name is &lt;b&gt;child2&lt;/b&gt;.
     &lt;/div&gt;
     &lt;div id=&quot;child3&quot; style=&quot;border: 1px solid purple; padding: 10px; margin: 10px;&quot;&gt;
          My name is &lt;b&gt;child3&lt;/b&gt;.
     &lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
Name of child element to be removed: &lt;input id=&quot;nameOfChild&quot; type=&quot;text&quot; value=&quot;child2&quot;&gt;&lt;input type=&quot;button&quot; value=&quot;Remove Element&quot; onClick=&quot;var name=document.getElementById('nameOfChild').value; removeElement('parentDiv', name);&quot;&gt;
&lt;br&gt;&lt;br&gt;
For those who are lazy in typing in the actual names, we have these handy-dandy buttons:
&lt;input type=&quot;button&quot; value=&quot;Remove child1&quot; onClick=&quot;removeElement('parentDiv', 'child1');&quot;&gt;
&lt;input type=&quot;button&quot; value=&quot;Remove child2&quot; onClick=&quot;removeElement('parentDiv', 'child2');&quot;&gt;
&lt;input type=&quot;button&quot; value=&quot;Remove child3&quot; onClick=&quot;removeElement('parentDiv', 'child3');&quot;&gt;
&lt;input type=&quot;button&quot; value=&quot;Remove parentDiv&quot; onClick=&quot;removeElement('parentDiv', 'parentDiv');&quot;&gt;</pre></td></tr></table></div>

<p>Here is a demo that removes child elements from the parent using checkboxes that a user would select.   This demo uses the same <b>removeElement</b> JavaScript function.</p>
<fieldset>
<legend>Demo</legend>
<div id="parentDivElement" style="border: 1px solid red; padding: 10px;">
     My name is <b>parentDivElement</b>.  I cannot be removed.</p>
<div id="childOne" style="border: 1px solid green; padding: 10px; margin: 10px;">
          My name is <b>childOne</b>.
     </div>
<div id="childTwo" style="border: 1px solid blue; padding: 10px; margin: 10px;">
          My name is <b>childTwo</b>.
     </div>
<div id="childThree" style="border: 1px solid purple; padding: 10px; margin: 10px;">
          My name is <b>childThree</b>.
     </div>
</div>
<p>&nbsp;</p>
<input id="cb1" type="checkbox" value="childOne" onclick="removeElement('parentDivElement', this.value);"><label for="cb1">Remove <b>childOne</b></label></p>
<input id="cb2" type="checkbox" value="childTwo" onclick="removeElement('parentDivElement', this.value);"><label for="cb2">Remove <b>childTwo</b></label></p>
<input id="cb3" type="checkbox" value="childThree" onclick="removeElement('parentDivElement', this.value);"><label for="cb3">Remove <b>childThree</b></label><br />
</fieldset>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">&lt;div id=&quot;parentDivElement&quot; style=&quot;border: 1px solid red; padding: 10px;&quot;&gt;
     My name is &lt;b&gt;parentDivElement&lt;/b&gt;.  I cannot be removed.
     &lt;div id=&quot;childOne&quot; style=&quot;border: 1px solid green; padding: 10px; margin: 10px;&quot;&gt;
          My name is &lt;b&gt;childOne&lt;/b&gt;.
     &lt;/div&gt;
     &lt;div id=&quot;childTwo&quot; style=&quot;border: 1px solid blue; padding: 10px; margin: 10px;&quot;&gt;
          My name is &lt;b&gt;childTwo&lt;/b&gt;.
     &lt;/div&gt;
     &lt;div id=&quot;childThree&quot; style=&quot;border: 1px solid purple; padding: 10px; margin: 10px;&quot;&gt;
          My name is &lt;b&gt;childThree&lt;/b&gt;.
     &lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;input id=&quot;cb1&quot; type=&quot;checkbox&quot; value=&quot;childOne&quot; onClick=&quot;removeElement('parentDivElement', this.value);&quot;&gt;&lt;label for=&quot;cb1&quot;&gt;Remove &lt;b&gt;childOne&lt;/b&gt;&lt;/label&gt;
&lt;input id=&quot;cb2&quot; type=&quot;checkbox&quot; value=&quot;childTwo&quot; onClick=&quot;removeElement('parentDivElement', this.value);&quot;&gt;&lt;label for=&quot;cb2&quot;&gt;Remove &lt;b&gt;childTwo&lt;/b&gt;&lt;/label&gt;
&lt;input id=&quot;cb3&quot; type=&quot;checkbox&quot; value=&quot;childThree&quot; onClick=&quot;removeElement('parentDivElement', this.value);&quot;&gt;&lt;label for=&quot;cb3&quot;&gt;Remove &lt;b&gt;childThree&lt;/b&gt;&lt;/label&gt;</pre></td></tr></table></div>

<p>The concept is the same as the previous demos where we attach the <b>removeElement</b> function to an event handler, which in this case is the <b>onClick</b> event handler of the checkbox.  Once the checkbox is checked (or even unchecked), it fires off the <b>onClick</b> event handler and executes the <b>removeElement</b> JavaScript function and passes off the name of the parent div and the value of the checkbox.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.randomsnippets.com/2008/03/26/how-to-dynamically-removedelete-elements-via-javascript/feed/</wfw:commentRss>
		<slash:comments>25</slash:comments>
		</item>
		<item>
		<title>How to find and replace text dynamically via JavaScript</title>
		<link>http://www.randomsnippets.com/2008/03/07/how-to-find-and-replace-text-dynamically-via-javascript/</link>
		<comments>http://www.randomsnippets.com/2008/03/07/how-to-find-and-replace-text-dynamically-via-javascript/#comments</comments>
		<pubDate>Fri, 07 Mar 2008 07:18:20 +0000</pubDate>
		<dc:creator>Knix</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[dynamic]]></category>
		<category><![CDATA[find]]></category>
		<category><![CDATA[find and replace]]></category>
		<category><![CDATA[findMyText]]></category>
		<category><![CDATA[haystack]]></category>
		<category><![CDATA[haystackText]]></category>
		<category><![CDATA[javascript function]]></category>
		<category><![CDATA[onclick event]]></category>
		<category><![CDATA[regex]]></category>
		<category><![CDATA[replace]]></category>
		<category><![CDATA[Replacement]]></category>
		<category><![CDATA[replacement text]]></category>
		<category><![CDATA[text replacement]]></category>

		<guid isPermaLink="false">http://www.randomsnippets.com/2008/03/07/how-to-find-and-replace-text-dynamically-via-javascript/</guid>
		<description><![CDATA[
This is a neat little script that demonstrates two things:
1) Find &#8211; If only the Find box is filled in, then the findMyText() JavaScript function will just perform a find for the div that is given.  If there is a match, the text will be highlighted and marked in bold.
2) Find and Replace &#8211; [...]]]></description>
			<content:encoded><![CDATA[<p><script src="/wp-includes/js/findAndReplace.js" language="Javascript" type="text/javascript"></script><br />
This is a neat little script that demonstrates two things:</p>
<p>1) <b>Find</b> &#8211; If only the <b>Find</b> box is filled in, then the <b>findMyText()</b> JavaScript function will just perform a find for the div that is given.  If there is a match, the text will be highlighted and marked in bold.</p>
<p>2) <b>Find and Replace</b> &#8211; If both the <b>Find</b> and <b>Replace</b> boxes are filled in, then the <b>findMyText()</b> JavaScript function will do just that. </p>
<fieldset>
<legend>Demo</legend>
<div id="haystack">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
<p></p>
<table>
<tr>
<td>Find</td>
<td>
<input id="needle" name="needle" type="text"></td>
</tr>
<tr>
<td>Replacment</td>
<td>
<input id="replacement" name="replacement" type="text"></td>
</tr>
</table>
<input type="button" value="Find" onClick="findMyText(document.getElementById('needle').value, document.getElementById('replacement').value);">
</fieldset>
<p><span id="more-11"></span><br />
Here is the plain HTML:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">&lt;div id=&quot;haystack&quot;&gt;
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
&lt;/div&gt;
&lt;br&gt;
&lt;table&gt;
&lt;tr&gt;&lt;td&gt;Find&lt;/td&gt;&lt;td&gt;&lt;input id=&quot;needle&quot; name=&quot;needle&quot; type=&quot;text&quot;&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Replacment&lt;/td&gt;&lt;td&gt;&lt;input id=&quot;replacement&quot; name=&quot;replacement&quot; type=&quot;text&quot;&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;
&lt;input type=&quot;button&quot; value=&quot;Find&quot; onClick=&quot;findMyText(document.getElementById('needle').value, document.getElementById('replacement').value);&quot;&gt;</pre></td></tr></table></div>

<p>
Please excuse the use of the table for the text inputs and labels.  WordPress does some automatic formatting which is annoying sometimes but it is still a great application =)  The only thing of importance here is on line 9 where the <b>onClick</b> event executes the <b>findMyText()</b> function and passes 2 arguments:</p>
<ul>
<li><b>Needle</b> &#8211; This is the text that we are trying to find in the haystack of text.</li>
<li><b>Replacement</b> &#8211; This is our replacement text for any needle that we find.</li>
</ul>
<p>Here is our JavaScript function:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
</pre></td><td class="code"><pre class="javascript javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> haystackText <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;&quot;</span>;
<span style="color: #003366; font-weight: bold;">function</span> findMyText<span style="color: #009900;">&#40;</span>needle<span style="color: #339933;">,</span> replacement<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
     <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>haystackText.<span style="color: #660066;">length</span> <span style="color: #339933;">==</span> 0<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
          haystackText <span style="color: #339933;">=</span> document.<span style="color: #660066;">getElementById</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;haystack&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">innerHTML</span>;
     <span style="color: #009900;">&#125;</span>
     <span style="color: #003366; font-weight: bold;">var</span> match <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> RegExp<span style="color: #009900;">&#40;</span>needle<span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;ig&quot;</span><span style="color: #009900;">&#41;</span>;     
     <span style="color: #003366; font-weight: bold;">var</span> replaced <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;&quot;</span>;
     <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>replacement.<span style="color: #660066;">length</span> <span style="color: #339933;">&gt;</span> 0<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
          replaced <span style="color: #339933;">=</span> haystackText.<span style="color: #660066;">replace</span><span style="color: #009900;">&#40;</span>match<span style="color: #339933;">,</span> replacement<span style="color: #009900;">&#41;</span>;
     <span style="color: #009900;">&#125;</span>
     <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
          <span style="color: #003366; font-weight: bold;">var</span> boldText <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;&lt;div style=<span style="color: #000099; font-weight: bold;">\&quot;</span>background-color: yellow; display: inline; font-weight: bold;<span style="color: #000099; font-weight: bold;">\&quot;</span>&gt;&quot;</span> <span style="color: #339933;">+</span> needle <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;&lt;/div&gt;&quot;</span>;
          replaced <span style="color: #339933;">=</span> haystackText.<span style="color: #660066;">replace</span><span style="color: #009900;">&#40;</span>match<span style="color: #339933;">,</span> boldText<span style="color: #009900;">&#41;</span>;
     <span style="color: #009900;">&#125;</span>
     document.<span style="color: #660066;">getElementById</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;haystack&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">innerHTML</span> <span style="color: #339933;">=</span> replaced;
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Like many of the scripts that you see here, using the JavaScript DOM objects is the key to doing the find and replace dynamically for our website.  </p>
<p>The script asks for two parameters: the needle which we are looking for in our text and the text we want to replace it with.  Please note that the replacement text is totally <i>optional</i>.  If no replacement text is given, then the behavior of the function changes a bit.</p>
<p>The <b>haystackText</b> variable is outside of the function in line 1 because we want to store the original text and always base our searches on the original text.  In lines 3-5 is where we store the original text in our <b>haystack</b> div if it is not already set.</p>
<p>Line 6 creates a regular expression object where we place our <b>needle</b> variable along with two flags:</p>
<ul>
<li><b>i</b> &#8211; This flag causes the regular expression match to be case-insensitive.</li>
<li><b>g</b> &#8211; This flag causes the regular expression match to be global so it matches every occurrence instead of just the first one.</li>
</ul>
<p>Lines 8-10 checks to see if the <b>replacement</b> text was set.  If so, we will use the <b>replace</b> method on our <b>haystackText</b> string object and feed it our <b>match</b> and <b>replacement</b> texts.  The resulting string will be saved in the <b>replaced</b> variable.</p>
<p>If the <b>replacement</b> text was not set, the <b>else</b> block in lines 11-14 will be executed.  We first prepare a variable of our <b>needle</b> that has a bit of extra styling such as a yellow background and bold text so it stands out better.  Next, we just use the <b>replace</b> method on our <b>haystackText</b> string object and pass the <b>match</b> and <b>replacement</b> texts.  The resulting string will be saved in the <b>replaced</b> variable.  </p>
<p>Lastly, the <b>replaced</b> variable which contains our results is used to substitute what was originally in our <b>haystack</b> div.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.randomsnippets.com/2008/03/07/how-to-find-and-replace-text-dynamically-via-javascript/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
	</channel>
</rss>
