Building dynamic form elements

Got the following HTML code:
<div class="hidden" id="ce_approval">
  <a href="#" class="custom_modal_close"></a>
  <input type="hidden" name="obleventcode" value="" id="obleventcode"/>
  <div class="oblcontent">
    <span>
      The information below is for adding CE Fees to the cart. Please select the state in which 
      you want to apply the CE for this course and then select the license type, if applicable and 
      click the Continue button.<br />
      Note: You may opt out of adding CE Fees by checking the OptOut checkbox.
    </span>
    <div class='ce_approval_html'>
      <select name="states" id="states_select">
      </select>
      <div class='spinner_add'><img src='/images/grey_spinner.gif'></div>
    </div>
    <div class="btnsCenter"><a href="#" class="btn left mr20 cancel">Cancel</a><a href="#" class="btn left continue">Continue</a></div>
  </div>
</div>

Open in new window


Along with this JSON:
{ "error" : "",
  "result" : { "OK" : "YES",
      "PurchaseRequisites" : { "PurchaseRequisite" : [ 
              { "AddItemNum" : null,
                "CeApprovals" : null,
                "Currency" : null,
                "ItemDescription" : null,
                "Mandatory" : null,
                "Price" : "0",
                "Qty" : "0"
              },
              { "AddItemNum" : "CE",
                "CeApprovals" : { "EventCeApproval" : [ 
                        { "CeHours" : "8",
                          "EveRid" : "144053",
                          "LicenseType" : [
                                  { "ADJ" : "Adjuster", 
                                     "LH" : "Life and Health"
                                   } ],
                          "Price" : "8",
                          "State" : "MO",
                          "StateName" : "MISSUORI"
                        },
                        { "CeHours" : "8",
                          "EveRid" : "144053",
                          "LicenseType" : null,
                          "Price" : "8",
                          "State" : "RI",
                          "StateName" : "RHODE ISLAND"
                        },
                        { "CeHours" : "8",
                          "EveRid" : "144053",
                          "LicenseType" : [
                                  { "ADJ" : "Adjuster", 
                                     "LH" : "Life and Health",
                                     "PC" : "Property and Casualty"
                                   } ],                                            
                          "Price" : "8",
                          "State" : "SD",
                          "StateName" : "SOUTH DAKOTA"
                       }
                      ] },
                "Currency" : "",
                "ItemDescription" : "CE Fee",
                "Mandatory" : "NO",
                "Price" : "0",
                "Qty" : "1"
              }
            ] },
      "Reason" : "NO ACTION REQUIRED",
      "Valid" : "YES"
    }
}

Open in new window


What I need to do is to clear the states select, iterate through the EvenCeApproval JSON and add each state.

When a state is selected, obtain the CEHours, LicenseType and Price and add hidden fields for CEHours
and Price and add radio buttons for each LicenseType below the state select. If LicenseType is null, no radios
need to be added.

When the Continue button is clicked, the Price, CEhours, selected LicenseType and EventCode (obleventcode) value
will be used to build a URL to be submitted via ajax.

Here's what code I have now. The sm_content object is a smart_modal window: http://charlesmarshall.co.uk/jquery/2009/04/29/jquery-modal.html.
The JSON is in the prereq varible. The show_ce_approval function is called when AddItemNum == 'CE'.

function show_ce_approval(prereq){
  $('#sm_content .oblcontent').html($('#ce_approval').html());
  $('#sm_content .ce_approval_html').html('Loading CE Fee Information.');
  // now iterate over the EventCEApproval items and populate the state dropdown. 
  // The hidden fields and license types will be populated when the state is selected.
  
  // clear all states currently in the select
  $("#sm_content .ce_approval_html select[name='states']").remove();
  for(var i in prereq.CeApprovals.EventCeApproval){
    statename = prereq.CeApprovals.EventCeApproval[i].StateName;
    stateabbr = prereq.CeApprovals.EventCeApproval[i].State;
    $("#sm_content select[name='states']").append(new Option(statename, stateabbr));
  }  
  $("#sm_content .ce_approval_html select[name='states']").change(build_ce_info(prereq));
  $('#sm_content a.cancel').click(function(){location.reload(true);});
  // $('#sm_content a.continue').click(add_ce_approval);
  $('html, body').animate({scrollTop:0}, 500);

  $('#sm_content .custom_modal_close').click(function(){
    $('.popup1').smart_modal_hide();
    return false;
  });
}

function build_ce_info(prereq) {
  // get the infor for the state
  state = this.value;
  for(var i in prereq.CeApprovals.EventCeApproval){
    if(prereq.CeApprovals.EventCeApproval[i].State == state) {
      cehrs     = prereq.CeApprovals.EventCeApproval[i].CeHours;
      ceprice   = prereq.CeApprovals.EventCeApproval[i].LicenseType;
      celictype = prereq.CeApprovals.EventCeApproval[i].Price;
      for(var j in prereq.CeApprovals.EventCeApproval[i].LicenseType) {
        celictype = prereq.CeApprovals.EventCeApproval.LicenseType[j][0];
        celicval  = prereq.CeApprovals.EventCeApproval.LicenseType[j][1];
        $("#sm_content.ce_approval_html  select[name='states']").after('<input type="radio" name="'+celicval+'" value="'+celicval+'" />'+celictype);
      }

      $("#sm_content .ce_approval_html select[name='states']").after('<input type="hidden" name="CeHours" value="'+cehrs+'">');
      $("#sm_content .ce_approval_html select[name='states']").after('<input type="hidden" name="CePrice" value="'+ceprice+'">');
      $("#sm_content .ce_approval_html select[name='states']").after('<input type="hidden" name="CeLicenseType" value="'+celictype+'">');
      $("#sm_content .ce_approval_html select[name='states']").after('<input type="checkbox" name="CeOptOut" value="OptOut"/>Opt Out of CE for this course');
    }
  }  
}

function add_ce_approval() {
  eventcode = $("#sm_content input[name='obleventcode']").val();
  cehrs     = $("#sm_content .ce_approval_html input[name='CeHours']").val();
  celictype = $("#sm_content.ce_approval_html  input[name='CeLicenseType']").val();
  ceprice   = $("#sm_content .ce_approval_html input[name='CePrice']").val();
  optout    = $("#sm_content .ce_approval_html input[name='CeOptOut']").checked();
  var url = AJAX_URL_ADDTOCART + '?sku=' + eventcode + '&price=' + ceprice + '&desc=' + celictype + ' CE Fees&optout='+optout;
  $.ajax({async: true, type:'POST',url: url, dataType: 'json', success: function(data){
        // 
     }
  });
}

Open in new window


I am stuck on how to finish this up. I do not see the select at all after the states are loaded.
LVL 26
Eddie ShipmanAll-around developerAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

leakim971PluritechnicianCommented:
May help you do some steps forward : http://jsfiddle.net/wwxKP/1/

0
leakim971PluritechnicianCommented:
    var json = {"error":"","result":{"OK":"YES","PurchaseRequisites":{"PurchaseRequisite":[{"AddItemNum":null,"CeApprovals":null,"Currency":null,"ItemDescription":null,"Mandatory":null,"Price":"0","Qty":"0"},{"AddItemNum":"CE","CeApprovals":{"EventCeApproval":[{"CeHours":"8","EveRid":"144053","LicenseType":[{"ADJ":"Adjuster","LH":"Life and Health"}],"Price":"11","State":"MO","StateName":"MISSUORI"},{"CeHours":"14","EveRid":"144053","LicenseType":null,"Price":"8","State":"RI","StateName":"RHODE ISLAND"},{"CeHours":"8","EveRid":"144053","LicenseType":[{"ADJ":"Adjuster","LH":"Life and Health","PC":"Property and Casualty"}],"Price":"8","State":"SD","StateName":"SOUTH DAKOTA"}]},"Currency":"","ItemDescription":"CE Fee","Mandatory":"NO","Price":"0","Qty":"1"}]},"Reason":"NO ACTION REQUIRED","Valid":"YES"}};

    $(document).ready(function() {
        show_ce_approval(json["result"]);
    });

    function show_ce_approval(prereq){
        //$('#sm_content .oblcontent').html($('#ce_approval').html());
        $('#sm_content .ce_approval_html').html('Loading CE Fee Information.');
        // now iterate over the EventCEApproval items and populate the state dropdown. 
        // The hidden fields and license types will be populated when the state is selected.
        
        // clear all states currently in the select
        $("#states_select").html(new Option("Choose one"),"");
        var EventsCEApproval = prereq.PurchaseRequisites.PurchaseRequisite[1]["CeApprovals"]["EventCeApproval"];
        for(var i=0;i<EventsCEApproval.length;i++) {
            statename = EventsCEApproval[i]["StateName"];
            stateabbr = EventsCEApproval[i]["State"];
            $("#states_select").append(new Option(statename, stateabbr));
        }  

        // eventcode is on every one so it is ok to get it here?
        eventcode = EventsCEApproval["EveRid"];
        $("#obleventcode").val(eventcode);
        $("#states_select").change([EventsCEApproval], build_ce_info);
        $('a.cancel').click(function(){ location.reload(true); });
        $('a.continue').click(add_ce_approval);
        $('html, body').animate({scrollTop:0}, 500);
        
        $('#sm_content .custom_modal_close').click(function(e) {
            e.preventDefault();
            $('.popup1').smart_modal_hide();
        });
    }
    
    function build_ce_info(evt) {
        var events_CE_Approval = evt.data[0];
        // get the info for the state
        var state = $(this).val();
        for(var i=0;i<events_CE_Approval.length;i++){
            if(events_CE_Approval[i]["State"] == state) {
                cehrs     = events_CE_Approval[i].CeHours;
                ceprice   = events_CE_Approval[i].LicenseType?events_CE_Approval[i].LicenseType[0]["ADJ"]:"";
                celictype = events_CE_Approval[i].Price;
                $("input[name='CEHours']").val(cehrs);
                $("input[name='CEPrice']").val(ceprice );
                $("input[name='CELicenseType']").val(celictype);
            }
        }  
    }
    
var AJAX_URL_ADDTOCART = "http://www.123soleil.com/page.xyz";
        
    function add_ce_approval() {
        eventcode = $("#obleventcode").val();
        cehrs     = $("#sm_content input[name='CEHours']").val();
        celictype = $("#sm_content input[name='CELicenseType']").val();
        ceprice   = $("#sm_content input[name='CEPrice']").val();
        var url = AJAX_URL_ADDTOCART + '?sku=' + eventcode + '&price=' + ceprice + '&desc=' + celictype + ' CE Fees';
        $(".spinner_add").show();
        alert(url); // for testing purpose
        $.ajax({ async: true, type:'POST',url: url, dataType: 'json', success: function(data){
            // go on to next step...
        }});
    }

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Eddie ShipmanAll-around developerAuthor Commented:
After some tweaking, it worked out just fine, thanks.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
jQuery

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.