21 June 2013

Best ways to build dynamic components in browser.

Long back in my projects we have done some terrible mistakes when creating dynamic HTML components on the current page that is being viewed. So thought to document the best ways to do this after discussion with some experts.

Problem :-

on the currently viewing page there is a checkbox. If user checks the checkbox then a combobox with the values coming from database should be displayed next to the checkbox.
                                                    OR
A combobox should be displayed with some specific values on the currently being viewed page when user selects an option in the combox that is already there on the page. I mean the dynamic combobox values depend on the option selected in the combox present on the page.

so how to achieve this?

Solution:-

well for these cases when a checkbox is checked or an option is selected on the cobbox, when these events occur an Ajax call should be triggered, it sends request to the servlet for data and then the servlet should return the values as JSON or XML, when the browser receives the response as JSON or XML then using javascript we have to parse the response and build the javascript string containing combobox code and then insert that into the DIV which displays it on HTML.  

The following snippet shows how to build combobox using javascript and insert into HTML:-




var selectHtml = '<select name="dibujoshechos" id="dibujoshechos">';
for (..){
    selectHtml += '<option>' + valueToBeDisplayed + '</option>';
}
selectHtml += '</select>';
$j('#someDiv').append(selectHtml)



On the server side to convert objects into JSON there are redymade libs available.

No comments: