Using JSF form fields with jQuery – Can’t use jQuery with : (colon) problem

if you have a jsf page of the following

<h:body>
<h:form id="frmRegistration">
<h:panelGrid columns="2" rules="rows">
<h:outputLabel id="lblFirstName" value="First Name"  />
<h:inputText id="txtFirstName" value="#{memberRegisterBean.member.name}" label="First Name" required="true"/>
.
.
.

And say you want assign default value from javascript to the text box you would use:

    $("#frmRegistration:txtFirstName").val("this val");

Since that is how JSF would generate the id of the component
But, you wont see any effect as jQuery don’ like the generated colon (:).
use this instead> ‘escape it’

    $("#frmRegistration\:txtFirstName").val("this val");

Adding Anchor to a text on the fly using jQuery

I come across the requirement where I need to create an anchor to a list based on some condition – hence I can go that specific anchor right away.

Though this can fairly and easily performed from the server side while the list is being prepared – without a bandwidth problem, I have found javascript method more fancy and easy. But, for the poor browser whose javascript is disabled, you might want to consider an alternative of server side.

Lets assume this simple scenario. You have list of completed and pending code statues. and Assume this list is longer and the completed list can appear in any place on the list but it is assured that all the completed lists would be all together.

So, all you want to do is to create an anchor to the very first of the completed list on the fly. Here is the snippet for that:

<!--
   __ __ _______
  | |/ /|    | |
  |   / | / | |
  | | | -- | |___
  |_| __||_|____| 

    Kaleb Woldearegay<contactkaleb@gmail.com>
 -->
<html>
<head><title>Simple </head>
<body>
<div id="completed"></div>
<table>
<tr>
    <td>1</td><td>code for module one</td>
</tr>
<tr>
    <td>2</td><td>code for module two</td>
</tr>
<tr class='completed'>
    <td>3</td><td>code for module 3</td>
</tr>
<tr class='completed'>
    <td>4</td><td>code for module 4</td>
</tr>
<tr class='completed'>
    <td>5</td><td>code for module 5</td>
</tr>
</table>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
        $(document).ready(function(){
                //perform only if there is atleast one completed row
                if ($("table tr.complete").length > 0){
            $("#completed").html("<a href='#anchored'>Go to Anchored</a>"); 
                        var completed = $("tr.complete:first").find("td:nth-child(2)");    //choose the second td
                        completed.html("<a name='anchored'>" + completed.html() + "</a>");//create the anchor
                        $("table tr.complete").css('background', 'green'); //colorize
        }  
                $("table tr.pending").css('background', '#cccFFF');
        });

</script>
</body>
</html>

Adding default option on the fly to select with jQuery, removing and some more…

How can I add or remove option dynamically on the select element using jQuery

Using the following snippet, you can do the following and related tasks of adding default options or working with elements that are created dynamically at the client side

  • How to add default option to select
  • How to manipulate elements that are created on the fly

Selecting element with multiple classes with jQuery

<html>
	<head><title>Adding default selection list</title>
	</head>	
	<body>
		<select name = "items" id="items">
			<option value="item1">Item One</option>
			<option value="item2">Item Two</option>
			<option value="item3">Item Three</option>
		</select>
		<input type = "button" name="checkme" id = "checkme" value='check me' />
		<p class='static'>Existing Paragraph</p>
		<div class='newly'></div>
		<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js"></script>
		<script>
			$('#items').prepend('<option value= '' selected='selected'>Select Item Please</option>');
			$('#checkme').click(function(){
				if ($('#items').val() != ""){
					$('<p>Yup you have selected ' + $('#items').val()+'<a href=''>delete</a></p>').appendTo('.newly');
				}else{
					alert('Plase select proper item');				
				}
			});
			$('p a').live('click',(function(){

				var remove = confirm("You sure to delete?");
				if (remove){
						$(this).parent().remove();
				}
  			return false;
			}));

		</script>
	</body>
</html>

The prepend function on the selected element would put the given element on top of the list – there is also an append version of it

It would be difficult to access the elements that are created on the fly/dynamically with jQuery without the use of live() – it binds the given click event to newly created elements.

Why binding/unbinding not working on firefox?

Finally, when we delete, we want to delete the the paragraph as the whole that contains the anchor. Most of the time we want to do it with in the div tag.

In this case the anchor (a) is a child of the paragraph (p) – that is where the .parent().remove() would come to play.

Populate selectbox from JSON with jQuery

Do you know how to add anchor dynamically to text?

CSS rendered different for local and remote servers

I was banging against the wall for this weirdest scenario.

When I run my site locally using the localhost, http://localhost/site.., all is good and the desired width and everything is OK.

When I publish my site on my server, all the CSS were jacked as if I have never tried it on my local machine before I publish it.

The browser is the same, the css and everything is the same but the rendering is different from local machine.

Trying to figure out, when I access my local site from my other computer, it is still jacked .. I said “HA!”.

Then I changed the localhost with my computer name and yup it is all messed up.
Tried to find out why apache is acting nice for local and strange for the other ones. But at least I can work on my local machine and publish it now.

Also, check if you have any reference of the css and javascript files with localhost.

find and filter in jQuery when and how to use

Thanks to JQuery, handling javascript has never been easy. Bigger things while working on the client side would be querying the DOM for specific components. Among the tremendously many options, I would discuss the find and filter.
For illustration of the discussion let’s have the following example HTML:

<div class="upper"><p>Upper text goes here</p><div>
<div class="upper"><p>Another <b>Upper text goes</b> here</p><div>
<div class="middle"><p>middle <b>text goes</b> here</p><div>
<div class="lower">lower <b>text goes</b> here<div>
<div class="lower"><p>still another lower <i>text goes</i> here</p><div>

Using Filter

Filter would provide all the given components which are screened by the given condition. the query:
jQuery(‘div’).filter(‘.upper’) would provide two elements of div that have class upper on them. so alert(jQuery(‘div’).filter(‘.upper’).length) would alert two. Changing the class to middle and lower would result one and two respectively.

Using Find

Find, like the filter would provide elements and unlike filter, it would apply filtering on the children of the given component. Here is an example

jQuery('div').find('p').addClass('border-it');

This query would select the ‘p’ tag under every div element and would apply the class ‘border-it’ to the ‘p’ element only. Which means, it would iterate on the given condition on the parent component.

Finding all the bolds and underlining them would be:

jQuery('div').find('p').find('b').css('text-decoration', 'underline');

Also, this can be done ins succinct way as:

jQuery('div p b').css('text-decoration','underline');

How about if we want to select both the parent and the selected child:

In this case the handy method andSelf() would be there. Say if we want to border only the bold text and that of the enclosing div, we would have:

jQuery('div').find('p').find('b').andSelf().css('border', '1px black solid');

Adding multiple javascript files to page

I was pulling my hair just for some silly stuff. All I wanted was to put two external javascript file for my floundering page – that was it!! and I do it as

<script language="javascript" src="sourceone" />
<script language="javascript" src="sourcetwo" />

BTW, I am using firefox on ubuntu, then when I try to run the page it would turn white. Astonishingly, the kick for the error was

<script language="javascript" src="sourceone"></script>
<script language="javascript" src="sourcetwo" ></script>

Hidden Frame Pattern / Pre-Ajax

This is one of the knows patterns in the web devs. The idea would be having two – or possibly more – frames and making one the front one for interaction while would be HIDDEN.
Why Hidden?
The visible frame would pass make a request to the hidden frame to make the server side interaction behalf of it. Doing so would make the visible frame to remain loaded. The hidden would play the rest of the game by consulting the server and grabbing all the required data. Of course, how do they talk? well, Mr. Javascript will be the ‘man in the middle’ – don’t wanna mention the security flaw known by this name 😉

Let’s see a quick example: the example will show how to interact with the server side script without page reload. For demo purpose, A page will accept first name and last name and will display the concatenated full name. Though the logic done is is too easy to accomplish, one has to bear in mind that any complex logic can be done in the same way.

First create a simple index file containing the frames

<html>
	<head><title>Lab01</title>
		<frameset rows="100%, 0" style="border: 0px">
			<frame name="visibleframe" src="enterName.html" noresize="noresize"></frame>
			<frame name="hiddenframe" src="about:blank" noresize="noresize"></frame>
		</frameset>
	</head>
</html>

Making the frameset row 100% will assure the full visibility.
Then have the page for first and last name.
enterName.html.


<script>
	//get full name by delegating the task to the php 
	function getFullName(){
		var firstName = document.getElementById("txtFirstName").value;
		var lastName = document.getElementById("txtLastName").value;
		top.frames["hiddenframe"].location = "concateName.php?firstName="+firstName+"&lastName="+lastName;
	}
	//display it on the front page 
	function showFullName(fullName){
		showdiv = document.getElementById("fullName");
		showdiv.innerHTML = fullName;
	}
</script>
Your First Name <input type="text" id = "txtFirstName" name="txtFirstName" /> <br>
YOur Last Name<input type="text" id="txtLastName" name="txtLastName" /> <br>

<input type="submit" name="subGetFullName" value = "concate" onClick="getFullName();" /> <br>
<textArea id="fullName" name="fullName"></textArea>

This file contains two javascripts: one for sending the form values to the hidden frame and the other to accept and display the result from the hidden frame.
Since the hidden frame had no source initially, the getFullName() function would be responsible for assigning the file to it.

Now lets build the server side script which will combine and return the full name
concateName.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head><title></title>
    <script>
    window.onload = function(){
       var fullNameDiv = document.getElementById("fullName");
       top.frames["visibleframe"].showFullName(fullNameDiv.innerHTML);
    };
    </script>
    <?php
        $firstName = $_GET['firstName'];
        $lastName = $_GET['lastName'];
        $fullName = $firstName . $lastName;
    ?>
    </head>
        <body><div id="fullName"><?php echo "FULL name is " . $fullName ?>
        </div></body>
</html>

Now we are done. :)
The concateName.php would get the parameters from the enterName.html through hiddenframe. Once it access the values, it will concatenate them and will deploy the result in the “fullName” div.
The defined window.onload would wait until things are in place and it will fire the result back to the “visibleframe” through javascript.
Now – the user has no what is going on behind he scene – as she will not see the page being reloaded on refreshed.

reference: Professional Ajax 2nd edition Wrox

jQuery – Simple & Powerful

jQuery seems the new player as far the client side manipulation is the issue. I had always thanked JavaScript for allowing us to do the dirty job on the client side starting from validation to amazing animations and magics – as it was seen on the Google earth, we should due credit.
Then comes Ajax, yup I have loved and played with it and it is so logical. Why do I have to submit the whole page while the intension is to submit only, say, a single value like an email for subscription. Of course it has done even more than that.
And now, jQuery which is a bundle of the two nice tools. JQuery is collection of JavaScript libraries that would make coding easy, fast navigation experience and almost a shortcut to Ajax.
The functions in the jQuery are human friendly and easy to remember.
It is possible to access an element only, or a group of elements or elements under the same class in easier way. Above all uses nicely callback functions – cooool.
All one has to do to start jQuery is to download the library from http://docs.jquery.com/Downloading_jQuery and locate it like any other JavaScript code:
Following this, be ready to plough. The main character in play would be the jquery object itself. Accessing it could be done either by directly calling it or using its alias($) – which is the custom to go. How it does is: first it would select single or group of elements and then apply tasks like editing, hide/show, replacing, assigning new style and many more. Let us use the following simpe XHTML code for illustration

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title> Sample jQuery </title>
<script src="JQuery/jquery-1.3.2.min.js" type="text/javascript" ></script>
<style type="text/css">
.highlight{
background-color: palegreen;
font-family: verdana;
color: black;
font-size: 12px;
width: 300px;
}
.emphasis{
text-weight: bold;
border: solid 1px blue;
width: 300px;
}
</style>

</head>

<body>
<p id="description" class="highlight">This is for the illustration purpose</p>
<p id="attention" class="emphasis">give attention for this</P>
<a href="http://www.devx.com/codemag/Article/40923/0/page/1">More examples</a>
<input type="button" id="toggler" value="toggle" />
</body>
</html>

Basic jQuery statement would have the following format:

<script type="text/javascript">
       $(document).ready( function(){
               logic goes here;
         });
</script>

Here the ‘$’ is an alias for the jQuery object, document is the representation of documents as in DOM. The ready method makes sure if the page is ok to proceed or not.
function() inside the ready() method is the callback function. The beauty begins here, we can define any function of our own as we like.
Lets remove the highlight style from description and assign it emphais
The first part “p#description” would select the paragraph with id description. Had it been “p”, it would select all paragraphs.
In this particular case it is also possible to say (“#description”).
removeClass and addClass are self-explanatory.
The chaining is possible as a dot operated methods because each selection would return an object.
Remember how to toggle in JavaScript? Had to use if .. how about in jQuery.
Lets make a click on the first paragraph to hide and show the second paragraph.

        $("#description").click( function(event){
              $("#attention").toggle();
        });

That is all. A single line would keep our fingers from being tired.

Here, the click method would accept the callback function. This call back function is specific to the call only. Say if I have used (“p”), then when I click on a particular <p>, the click method would be applicable only to the clicked paragraph element.

	$("p#description").click(function(event){
            $(this).hide();$("p#attention").show();
        });
	$("p#attention").click(function(event){
            $(this).hide();$("p#description").show();
        });

The above snippet shows only one paragraph at a time. But it shows them alternatively.

This is just to give a very highlight about jQuery. There are a lot of things especially on the selection area.

The following are are good sources of jQuery tutorial and references
jQuery.com
http://www.devx.com/codemag/Article/40923/0/page/1
http://roshanbh.com.np/2008/03/jquery-benefits-examples-free-ebook.html