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?

DataBinding: ‘System.String’ does not contain a property with the name ‘Value’.

I had to work a very simple implementation for a dot net page where on the dropdownlist I had to bind string values from ArrayList and Hashtable.
When the data was loaded from hash table and then from the ArrayList was the situation to got this error.
The reason behind is, while using the Hashtable, I has assigned for key and value to be populated from the hash table, this said, when I populate it from the ArrayList, the control tries to assign value and key from the object inside the ArrayList which was plain String which doesn’t have value property.
Simple remedy:
1. Assign the key and values to null on the case of the ArrayList OR
2. Wrap the string other object and provide a property of Value – I haven’t tried it, but in principle, it should work.

Here is a snippet of the code behind:

  1. protected void btnArrayList_Click(object sender, EventArgs e)
  2.         {
  3.             ArrayList list = new ArrayList();
  4.             list.Add("Name one");
  5.             list.Add("Name two");
  6.             list.Add("Name three");
  7.             list.Add("Name four");
  8.             DropDownList1.DataSource = list;
  9.             DropDownList1.DataTextField = null;
  10.             DropDownList1.DataValueField = null;
  11.             DropDownList1.DataBind();
  12.         }
  13.  
  14.         protected void btnHashTable_Click(object sender, EventArgs e)
  15.         {
  16.             Hashtable table = new Hashtable();
  17.             table.Add("one", "name one");
  18.             table.Add("two", "name two");
  19.             table.Add("three", "name three");
  20.             table.Add("four", "name four");
  21.             table.Add("five", "name five");
  22.             DropDownList1.DataSource = table;
  23.             DropDownList1.DataTextField = "Value";
  24.             DropDownList1.DataValueField = "Key";
  25.             DropDownList1.DataBind();
  26.         }
  27.  

Happy DataBinding.

NonUniqueObjectException: a different object with the same identifier value was already associated with the session

The error different object with the same identifier value was already associated with the session would happen quite sometime while working on hibernate with java web application

It occurs when the hibernate session contains object to be updated and when the application tries to update another object with the same id as that of the session owned one.

Let’s assume there is an object Can with properties material and volume as follows for simple illustration


public class Can{
  private Integer canId;
  private String material;
  private Double volume;
  //getters; setters;
}

Assume we have DAO for this object named CanDao.

So, being on your jsf dataTable you selected one ‘can’ object to be updated or deleted. I just put the CanDao object directly into the Bean for the illustration purpose – it is good to wrap this object in the service object, say CanService, for easier manupulation.

Lets have the bean as follows:


class CanBean{
   private HtmlDataTable canTable; //for binding list of can objects from jsf list
   private CanDao canDao; //dao object;
   private List cans; //list jsf datatable would use it.
   .
   .
   .
   public String update(){
      //get the selected object from data table
      ICan selectedCan = (ICan)this.canTable.getRowData();
      this.canDao.saveOrUpdate(selectdCan);
      return "Update";
   }
}

Here the line calling saveOrUpdate would be responsible for throwing the error of different object with the same identifier value was already associated with the session

Here is how to fix it
Since the session contain the same identifier, let’s get the actual or original object from the session it self


  //corrected update method for Can Bean
   public String update(){
      //get the selected object from data table
      ICan selectedCan = (ICan)this.canTable.getRowData();
      ICan original = this.canDao.getById(selectedCan.getCanId()); //
      original.setVolume(selectedCan.getVolume());      
      original.setMaterial(selectedCan.getMaterial());
      this.canDao.saveOrUpdate(original);
      return "Update";
   }

This would fix the problem. But, there are other ways of preventing the session problem from occurring – googling a bit might help.

If you are J2EE developer:

Hello world with maven step by step

See how you can add session bean

Why do I get can not forward after response error and how to solve it

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.

Bean CurrentlyInCreationException: Error creating bean with name : Requested bean is currently in creation: Is there an unresolvable circular reference?

This CurrentlyInCreationExceptionexception happens during the construction of the bean.

If the bean has reference to other beans, and if those beans which are referenced have the this bean as property or constructor parameter, then it would be cyclic and hence this exception would be thrown.

So, check if you have beans that are referring to each other on you hbm/annotations files.

Accessing XML column of SQL Server from PHP (PDO)

One cool feature that SQL Server provides is the XML data type. This enables to save XML data as it is just like any other data type in the database.

Once we put the xml, then we can apply XPath to query the data from the sql server nifty IDE.

But, when you try to use the same query outside of the IDE, you would not be able to get the data as expected.

I was working on PHP project where the data (XML) has to be retrieved from SQL Server. Here is the hack step by step

1. Configure your PDO
Say:


try {
    $hostname = "host";            //host
    $dbname = "dbname";            //db name
    $username = "user";            // username like 'sa'
    $pw = "pass";                // password for the user

    $dbh = new PDO ("mssql:host=$hostname;dbname=$dbname","$username","$pw");
  } catch (PDOException $e) {
    echo "Failed to get DB handle: " . $e->getMessage() . "n";
    exit;
  } 
**taken from php.net

2. Once you got the handle ($dbh) add the following on the handle:


$handle = getHandle(); //function like above to give you the handle
$handle->exec('SET QUOTED_IDENTIFIER ON');
$handle->exec('SET ANSI_WARNINGS ON');
$handle->exec('SET ANSI_PADDING ON');
$handle->exec('SET ANSI_NULLS ON');
$handle->exec('SET CONCAT_NULL_YIELDS_NULL ON');

That is all, this are actually additional parameters that sql server would add when sending xml based query to the engine.

Happy XMLing :)