Tuesday 18 June 2013

Dynamic Divs via JQuery

In a secure session for our customers with XXX company, we wanted to give them a simplistic wizard to modify as much data as possible in a consistent and context relevant way. This wizard took a gigantic form built and parsed by PHP and added some dynamic content and validation to it via JQuery.

i.e.
<form>  
   <div>  
   //heaps of content  
      <table>  
      //heaps of content  
      </table>  
   </div>
   <div>
   //more something
   </div>  
</form>  

My first step was adding in id's for every div, every table, everything. You can never have enough items in your code identified.

<div id="this_is_a_div">  

Then I broke each section of the form into div's that are contextually related and had them not displayed by default. (a common class would be preferable to manually styling each div)

<div id="address_container" style="display:none;">  
   <div id="street_container" class="pre_defined_css">  
      <small class="input_info">Some random tool tip</small>
      <label for="street" class="label">Street</label>
      <input type="street" name="street" id="street" value="" class="input"class="label" /<
   </div>
</div>

This allows you to insert fancy Javascript. I personally like JQuery, a Javascript library which features a simple and powerful API to manipulate HTML. (works well with PHP too)

Assuming we have a button that activates a JS function like so:

<button type="button" id="reveal" class="button special-css" onClick="return reveal('address_container')">Reveal Button!</button>

We can build our function reveal. I'll show standard Javascript first then JQuery.

 function reveal(option) {  
   if(option == "a_div") {  
    document.getElementById("address_container").style.display = "block";  
    document.getElementById("another_div").style.display = "none";  
   }  
 }  

Or you can do it via JQuery
Edit: Don't forget to import JQuery first!!

 <script src="js/libs/jquery-1.8.2.min.js"></script>  

 function reveal(option) {  
   if(option == "a_div") {  
    $('#address_container').show();  
    $('#another_div').hide();  
   }  
 }  

Additionally, you can use the method toggle to contextual swap between show and hide calls depending on element state.

This allows you to build a 'wizard' or more simplistic form where each div is rendered by using 'next' buttons instead of showing all field and forms at once to the end-user.


No comments:

Post a Comment