Dynamically add DOM elements with jQuery

By | March 9, 2011

Ok so someone at work has built a form and then the boss comes back and says he wants to cross sell the products entered into the input fields by dynamically creating a list with links to alternative products and accessories. Unfortunately the person who has built the form page is away so you’ve got to pick the job up. Luckily you’ve got jQuery to use so that should make things a bit easier. So how do we approach this problem and where do we start?

First things first…

Rightly or wrongly you’ve got to start to make some decisions on how to go about solving the problems. In my case I’m quite lucky because my boss is very opinionated and knows exactly what he wants, so the brief is pretty set from the start so the issues I have are:

  • When the product code is added show links to alternative products and accessories
  • Delete alternative product links if the product code is deleted
  • Update alternative product links if the product code is updated

But there is another issue for me. My colleague has created the form in such a way that extra input areas can be added if there are not enough for you to enter all of your products.
This presents me with another issue. How do I get the value from an input element that hasn’t been created yet and use it to populate a list item dynamically?

Heres the plan

After you enter the product code and you leave (on blur) the input field (to go to the next part of the form), read the contents (or value) of the field and add it to the list (unless the contents are empty then do nothing). But there is more to the product code that we entered, because it is unique I am going to use this as an id on the list items then I can reference them later to delete the item (or update) if needed. I will also be putting the prodcut code into the href attribute of the ‘a’ tags within the list item.
The second part of the problem is on focus (when you click in the input item) if there is a value in the input field read it and delete the item with the same id as the value, then when you change the contents and click away it will add a new item with the new contents. So thats about it.

HTML Codes

    

So we have a 3 input elements to begin with and a button underneath that will be used to add more input fields. I’ve added a div container with an id around the input items so we can easily add more inputs. We’ve also got an empty unordered list that will be populated with the links.

jQuery and pure javascript

This is how I prefer to code. Many people like to use jquery for everything, I like to use it as a shortcut. JQuery’s selector engine is for me what makes it a joy to work with so thats the main thing I use it for.

    

First of all bring in jQuery. Then:

    	$(document).ready(function(){
			
			$('#addInputs').click(function(event){
					event.preventDefault();
					addInputEl() ;
   			});
			
			$('.textInput').live('blur', function(e) {
     			prodCode = this.value;
					addElement(prodCode) ;
   			});
			
			$('.textInput').live('focus', function(e) {
     				prodCode = this.value;
					checkElement(prodCode) ;
   			});
	
 		});

Add the event listeners. In simple terms the event listeners are attached to certain elements within your web page and when that event happens they tell the javascript (and almost always the page) to do something.
So from the top when the document is ready “$(document).ready” do what ever is there. Which is: find the element with an id of addInputs and add event listener so that when that element is clicked run event.preventDefault function and addInputEl function (we’ll get on to those in a minute).
Now the next two event handlers are what make this whole page work. We are going to use the jquery live method which does (to use the explanation off the jQuery site:

Attach a handler to the event for all elements which match the current selector, now and in the future.

Basically you can create (in our case blur and focus) event handlers for elements on the page but also for ones that haven’t been added yet. This is perfect for us because we have some input elements on the page that need the blur and focus event handlers adding but we may create more of these elements. By using live() when we do create more elements the blur and focus handlers will be attached to them.

So what do these event handlers do?

So the first handler looks after any click events on the element with the id of addInputs. This is actually a submit button so the first part of the code

   event.preventDefault();

justs prevents the default behavior of that button (so it doesn’t submit the form) take this bit out and you will see the input fields being added then disappear as the form is submitted and the page is refreshed. The second part of the handler is just a function so lets have a look at that.

function addInputEl(){
	inCon = document.getElementById('inputList');
	newP = document.createElement('p');
	newInput = document.createElement('input');
	newInput.setAttribute('class', 'textInput');
	newInput.setAttribute('type', 'text');
				
	newP.appendChild(newInput);
	inCon.appendChild(newP);
}

This is just javascript no help from jQuery here, you could use it but I prefer this method. So line by line we grab the element with an id of inputList and put it in a variable, then we create an ‘p’ tag element and assign it to a variable and the same for an input element. Then we create 2 attributes for the input element giving it a class of textInput (which we will use later) and a type of text( in the real life version there are more attributes.) Then all we do append the input tag to the ‘p’ tag and ‘p’ to the inputList div. By appending it just means it’s put inside the tag after anything else that my be in there.
Next the blur event handler:

	function addElement(code) {
	        pCd = code;
		if(pCd === ""){
			}	else{			
				list = document.getElementById('update_list');
				newLi= document.createElement('li');
				hTag= document.createElement('h1');
				midTag= document.createElement('p');
				botTag= document.createElement('p');
				midATag= document.createElement('a');
				botATag= document.createElement('a');
				
				newLi.setAttribute('id','prod_'+pCd);			
				midATag.setAttribute('href','http://www.my-html-codes.com?id='+pCd);
				botATag.setAttribute('href','http://www.my-html-codes.com?id='+pCd);
				
				midATag.innerHTML = 'Check for alternatives';
				botATag.innerHTML = 'Check for accessories';
				hTag.innerHTML = 'Product: '+pCd;
				midTag.appendChild(midATag);
				botTag.appendChild(botATag);
				newLi.appendChild(hTag);
				newLi.appendChild(midTag);
				newLi.appendChild(botTag);
				list.appendChild(newLi);
			}
		}

This function takes an argument which is the value of the input element , then it checks to see if the value is nothing if it is nothing happens. If it is not empty it grabs the ul by it’s id of update_list. Then we create all the elements we need so an ‘li’, ‘h1’ two ‘p’ tags and two ‘a’ tags. Then we set an id attribute on the li tag to ‘prod_’ plus the product code the the finished id will read something like ‘prod_123456’. We also set the href of the two a tags to the url plus the product code so they will end up looking something like ‘http://www.my-html-codes.com?id=123456’. Then we create the text to go inside the tags. And after that we append all the tags together then finally appending the list item to the ul. All the hard work for this project is done here.
Lastly the focus handler:

function checkElement(code) {
	pCd = code;
	if(pCd === ""){
	}else{	
		prodId = 'prod_'+pCd;
		cld = document.getElementById(prodId);
                pt = document.getElementById('update_list');
                pt.removeChild(cld);
		}
	}

So when we click into an input element we check again to see if it’s empty. If it is do nothing otherwise we recreate an id variable and then get the list item with that id. We also get the update list by it’s id and then we delete the list item from the list.
And that’s it it works a treat and it you want to see it working click the DEMO

4 thoughts on “Dynamically add DOM elements with jQuery

Leave a Reply

Your email address will not be published. Required fields are marked *