Solved

jQuery function/plugin - Loop through JSON object and updated HTML form elements

Posted on 2011-02-17
9
1,092 Views
Last Modified: 2012-05-11
I am having a JSON string be serialized after form submit. I have it returning this format: http://tobiascohen.com/files/stackoverflow/jquery-form-serializeObject.html - submit the form

I am trying to get a function where I can pass the JSON object and run it through a loop to update:

- inputs
- select
- radio
- check

if present. Instead of listing out each line of code for every input. If I make it run through a loop I can keep it dynamic, save code and use it for other areas.

Any ideas?

Thanks.
0
Comment
  • 6
  • 2
9 Comments
 
LVL 27

Expert Comment

by:BigRat
Comment Utility
I'm surprised that there isn't something like this already available. However I have something in which is similar to XML and it goes like this :-

function ratlUpdateForm(xml) {
   var dataNodes = xml.selectNodes('/result/data/*');
   for(var i=0; i<dataNodes.length; i++) {
      var node = dataNodes[i];
      var nodeName = node.nodeName;
      var docNode = document.getElementById(nodeName);
      if(docNode!=null) 
         var typeName = (docNode.type?docNode.type:docNode.tagName);
         if(typeName=='checkbox') {
            // check the box
            ratSetCheckBox(docNode,node.text);
         } else if(typeName=='radio') {
            ratSetRadioValue(docNode,node.text);
         } else if(typeName=='select') {
            ratSetSelectValue(docNode,node.text);
         } else if(typeName=='DIV') {
            docNode.innerHTML=node.text;
         } else if(typeName=='SPAN') {
            docNode.innerText=node.text;
         } else if(typeName=='IMG') {
            docNode.src=node.text;
         } else {
            // text box types (text/hidden/textarea/password)
            docNode.value=node.text;
            if(docNode.onblur) docNode.onblur();
         }
   }
}

The auxillary functions are :-

function ratSetCheckBox(boxNode,text) {
   boxNode.checked=(text=='1');
}

function ratSetSelectValue(selectObj,newValue) {
   for(var i=0;i<selectObj.options.length;i++) {
      if (newValue==selectObj.options[i].value) {
         selectObj.options[i].selected=true;
      }
   }
}

function ratSetRadioValue(radioObj, newValue) {
	if(!radioObj) return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
	}
}

so I hope that will be a start. You just need to take the JSON string and turn it into a list of name/value pairs (in an array) and loop through it doing the document.getElementById().

Open in new window

0
 
LVL 20

Accepted Solution

by:
Proculopsis earned 500 total points
Comment Utility

I think you need a function like this:

function loadForm( jsonString ) {
  var formData;
  eval( "formData = " + jsonString );
  for ( var member in formData ) {
    var formField = $("form>*[name='" + member + "']");
    switch ( formField.attr("type") ) {
      case "text":
      case "textarea":
      case "select-one":
        formField.val( formData[member] );
      break;
      case "radio":
      case "checkbox":
        $(formField).each( function() {
          $(this).attr( { checked: ( $(this).val() == formData[member] ) } );
        });
      break;
      default:
        alert( formField.attr("type") );
      break;
    }
  }
}

Open in new window


Here's a working example:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_26828499.html</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://jquery-json.googlecode.com/files/jquery.json-1.3.min.js"></script>
<script type="text/javascript">

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};
 
jQuery(document).ready( function () {

  $('form').submit(function() {
    alert($.toJSON($('form').serializeObject()));
    return false;
  });

  $("#load").click( function() {
    loadForm( $("#source").val() );
  });

});

function loadForm( jsonString ) {
  var formData;
  eval( "formData = " + jsonString );
  for ( var member in formData ) {
    var formField = $("form>*[name='" + member + "']");
    switch ( formField.attr("type") ) {
      case "text":
      case "textarea":
      case "select-one":
        formField.val( formData[member] );
      break;
      case "radio":
      case "checkbox":
        $(formField).each( function() {
          $(this).attr( { checked: ( $(this).val() == formData[member] ) } );
        });
      break;
      default:
        alert( formField.attr("type") );
      break;
    }
  }
}

</script>
<body>

<textarea id="source" cols="100" rows="3">
{"Fname": "First", "Lname": "Last", "gender": "Male", "food[]": "Pizza", "quote": "Remember the Alamo", "education": "College", "TofD": "Night"}
</textarea>
<input id="load" type="button" value="Load" />

<form action="" method="post"> <br/>
First Name:<input type="text" name="Fname" maxlength="12" size="12"/> <br/>
Last Name:<input type="text" name="Lname" maxlength="36" size="12"/> <br/>
Gender:<br/>
Male:<input type="radio" name="gender" value="Male"/><br/>
Female:<input type="radio" name="gender" value="Female"/><br/>
Favorite Food:<br/>
Steak:<input type="checkbox" name="food[]" value="Steak"/><br/>
Pizza:<input type="checkbox" name="food[]" value="Pizza"/><br/>
Chicken:<input type="checkbox" name="food[]" value="Chicken"/><br/>
<textarea wrap="physical" cols="20" name="quote" rows="5">Enter your favorite quote!</textarea><br/>
Select a Level of Education:<br/>
<select name="education">
<option value="Jr.High">Jr.High</option>
<option value="HighSchool">HighSchool</option>
<option value="College">College</option></select><br/>
Select your favorite time of day:<br/>
<select size="3" name="TofD">
<option value="Morning">Morning</option>
<option value="Day">Day</option>
<option value="Night">Night</option></select>
<p><input type="submit" /></p>
</form>
 
</body>
</html>

Open in new window

0
 
LVL 1

Author Comment

by:catonthecouchproductions
Comment Utility
Proculopsis: going to go try this out, I will let you know how it works out.

Thanks for this.
0
 
LVL 1

Author Comment

by:catonthecouchproductions
Comment Utility
This is what I have now
 
function loadForm(saveObjectName, formNameSel) {
    console.log("object: " + saveObjectName);
    for (var member in saveObjectName) {
        var formField = $(""+formNameSel+">*[name='" + member + "']");
        console.log(formField);
        switch (formField.attr("type")) {
            case "text":
            case "textarea":
            case "select-one":
                formField.val(formData[member]);
                break;
            case "radio":
            case "checkbox":
                $(formField).each(function () {
                    $(this).attr({ checked: ($(this).val() == formData[member]) });
                });
                break;
            default:
                alert(formField.attr("type"));
                break;
        }
    }
}

Open in new window


When i debug and view the selector inside the for loop. It returns the # for MEMBER not the name of the input/josn
0
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
LVL 1

Author Comment

by:catonthecouchproductions
Comment Utility
I have this that runs on save:

    saveTemp = $("form.validateDialog").serializeObject();
    saveObjectName.push(saveTemp);

Does that look right take the serialized data and push to the object saveObjectName (this is passed as a parameter in a function)
0
 
LVL 1

Author Comment

by:catonthecouchproductions
Comment Utility
And this alert returns undefined:

alert(formField.attr("type"));
0
 
LVL 20

Expert Comment

by:Proculopsis
Comment Utility

Need to see the json string and html to fine tune this solution.
0
 
LVL 1

Author Comment

by:catonthecouchproductions
Comment Utility
I was able to work with this and tweak the changes, solid function! I am working on a similar format but slightly different. If I paste could you tell me quickly if it would work for a string similar to this if not, I  can open a new question if you would prefer. Similar concept but different string.

String:
 
var invoice = {
        "Importer": "123456",

        "ImporterContact": {
            "Name": "test_importer_contact"
        },
        "InvoiceNo": "5436345",

        "InvoiceType": "L",
        "Supplier": {
            "Name": "test_supplier_name",

            "Street1": "test_supplier_street1",
            "Street2": "test_supplier_street2",

            "City": "test_supplier_city",
            "State": "test_supplier_state",

            "PostCode": "test_supplier_postcode",
            "Country": "test_supplier_country",

            "Phone": "test_supplier_phone",
            "IRSNo": "test_supplier_irs_no",

            "MID": "test_supplier_mid",
            "Type": 0,
            "PNCEmail": "test_supplier_pncemail"

        },
        "Exporter": {
            "Name": "test_exporter_name",
            "Street1": "test_exporter_street1",

            "Street2": "test_exporter_street2",
            "City": "test_exporter_city",

            "State": "test_exporter_state",
            "PostCode": "test_exporter_postcode",

            "Country": "test_exporter_country",
            "Phone": "test_exporter_phone",

            "IRSNo": "test_exporter_irs_no",
            "MID": "test_exporter_mid",

            "Type": 0,
            "PNCEmail": "test_exporter_pncemail"
        },
        "UCons": {

            "Name": "test_ucons_name",
            "Street1": "test_ucons_street1",

            "Street2": "test_ucons_street2",
            "City": "test_ucons_city",

            "State": "test_ucons_state",
            "PostCode": "test_ucons_postcode",

            "Country": "test_ucons_country",
            "Phone": "test_ucons_phone",

            "IRSNo": "test_ucons_irs_no",
            "MID": "test_ucons_mid",

            "Type": 0,
            "PNCEmail": "test_ucons_pncemail"
        },
        "Buyer": {

            "Name": "test_buyer_name",
            "Street1": "test_buyer_street1",

            "Street2": "test_buyer_street2",
            "City": "test_buyer_city",

            "State": "test_buyer_state",
            "PostCode": "test_buyer_postcode",

            "Country": "test_buyer_country",
            "Phone": "test_buyer_phone",

            "IRSNo": "test_buyer_irs_no",
            "MID": "test_buyer_mid",

            "Type": 0,
            "PNCEmail": "test_buyer_pncemail"
        },
        "ReleasePort": "test_release_port",

        "InvoiceDate": "11/24/2010",
        "Currency": "US",

        "EntryNo": "235",
        "TransType": "Consignment",

        "ReferenceNumber": [
        "3425345",
        "43568433",
        "3453456"


    ],
        "PaymentTerms": "Basics",

        "TotalAmount": 2500.75,
        "GrossWeight": 245.76,
        "BillLading": [
        {

            "BillLadingNo": "test_bill_lading_no1",
            "BillLadingQty": 35,

            "BillLadingUOM": "1N",
            "BillLadingSCAC": "test_1234",

            "BillLadingType": "M"
        },
        {
            "BillLadingNo": "test_bill_lading_no2",

            "BillLadingQty": 10,
            "BillLadingUOM": "1N",
            "BillLadingSCAC": "test_1056",

            "BillLadingType": "M"
        }
    ],
        "FeePercent": 92,
        "DiscountValue": 175.00,

        "FreightCurrency": "United States of America",
        "DiscountCurrency": "United States of America",
        "InsuranceCurrency": "United States of America",

        "InsuranceCharges": 25.00,
        "Freight": 550.00,
        "ArrivalDate": "11/30/2010",

        "SCACCode": "ABCD",
        "TotalUnitsShipped": 17,
        "DeliveryTerms": "Cost Ins. and Freight to Dest.",

        "BrokerProductDesc": "test_broker_product_descripton",
        "TotalDue": 2800.00,

        "UOM": "Bale",
        "RelatedParty": "Y",

        "CountryOfExport": "United State of America",
        "ExportDate": "10/16/2010",

        "Charges": 400.00,
        "RelatedDoc": [
        { "Id": "2626AAG", "Number": "2462442" },

        { "Id": "24627AH", "Number": "8835833" },

    ],
        "VesselName": "test_vessel_name",
        "VesselNo": "2364",

        "PortLading": "test_port_lading",
        "ContainerNum": [
        "235265233",
        "623663666",
        "823826262"
    ],
        "LocationQualifier": "test_location_qualifier",

        "LocationIndicator": "test_location_indicator",
        "LocationCode": "test_location_code",

        "USCLocation": "test_usc_location",
        "MarksNumbers": "test_marks_numbers",

        "PaymentBy": "Shipper",
        "Insured": "Y",

        "IT": [
        {
            "Date": "11/11/2010",
            "Number": "test_it_number11451",

            "PortUnlading": "test_port_unlading11"
        },
        {
            "Date": "11/10/2010",

            "Number": "test_it_number2",
            "PortUnlading": "test_port_unlading2"

        }
    ],
        "DateSubmitted": "10/22/2010",
        "DateCreated": "10/22/2010",

        "UserName": "test_username",
        "PNCImage": "",

        "Template": false,
        "LineItem": [

    ]
    };

Open in new window


How I am currently loading the data from the string above:
 
// Load supplier data
    if (invoice.Supplier.length != 0) {
        var supplier_display = invoice.Supplier;
        var supplier_load_input = '';
        supplier_load_input = supplier_display.Name + " - " + supplier_display.Street1 + " - " + supplier_display.Street2 + " - " + supplier_display.City + " - " + supplier_display.State + " - " + supplier_display.PostCode;
        $("input.supplier_party").val(supplier_load_input);
        $("div.supplier_load_box").show();

        $("#invoice_no_" + invNo + " .supplier_load_box .ship_party_name").html(supplier_display.Name);
        $("#invoice_no_" + invNo + " .supplier_load_box .ship_party_street1").html(supplier_display.Street1);
        $("#invoice_no_" + invNo + " .supplier_load_box .ship_party_street2").html(supplier_display.Street2);
        $("#invoice_no_" + invNo + " .supplier_load_box .ship_party_city").html(supplier_display.City);
        $("#invoice_no_" + invNo + " .supplier_load_box .ship_party_state").html(supplier_display.State);
        $("#invoice_no_" + invNo + " .supplier_load_box .ship_party_post_code").html(supplier_display.PostCode);
        $("#invoice_no_" + invNo + " .supplier_load_box .ship_party_country").html(supplier_display.Country);
        $("#invoice_no_" + invNo + " .supplier_load_box .ship_party_phone").html(supplier_display.Phone);
    }

    // Load exporter data
    if (invoice.Exporter.length != 0) {
        var exporter_display = invoice.Exporter;
        var exporter_load_input = '';
        exporter_load_input = exporter_display.Name + " - " + exporter_display.Street1 + " - " + exporter_display.Street2 + " - " + exporter_display.City + " - " + exporter_display.State + " - " + exporter_display.PostCode;
        $("input.exporter_party").val(exporter_load_input);
        $("div.exporter_load_box").show();

        $("#invoice_no_" + invNo + " .exporter_load_box .ship_party_name").html(exporter_display.Name);
        $("#invoice_no_" + invNo + " .exporter_load_box .ship_party_street1").html(exporter_display.Street1);
        $("#invoice_no_" + invNo + " .exporter_load_box .ship_party_street2").html(exporter_display.Street2);
        $("#invoice_no_" + invNo + " .exporter_load_box .ship_party_city").html(exporter_display.City);
        $("#invoice_no_" + invNo + " .exporter_load_box .ship_party_state").html(exporter_display.State);
        $("#invoice_no_" + invNo + " .exporter_load_box .ship_party_post_code").html(exporter_display.PostCode);
        $("#invoice_no_" + invNo + " .exporter_load_box .ship_party_country").html(exporter_display.Country);
        $("#invoice_no_" + invNo + " .exporter_load_box .ship_party_phone").html(exporter_display.Phone);
    }
    // Load consginee data
    if (invoice.UCons.length != 0) {
        var ucons_display = invoice.UCons;
        var ucons_load_input = '';
        ucons_load_input = ucons_display.Name + " - " + ucons_display.Street1 + " - " + ucons_display.Street2 + " - " + ucons_display.City + " - " + ucons_display.State + " - " + ucons_display.PostCode;
        $("input.consignee_party").val(ucons_load_input);
        $("div.consignee_load_box").show();

        $("#invoice_no_" + invNo + " .consignee_load_box .ship_party_name").html(ucons_display.Name);
        $("#invoice_no_" + invNo + " .consignee_load_box .ship_party_street1").html(ucons_display.Street1);
        $("#invoice_no_" + invNo + " .consignee_load_box .ship_party_street2").html(ucons_display.Street2);
        $("#invoice_no_" + invNo + " .consignee_load_box .ship_party_city").html(ucons_display.City);
        $("#invoice_no_" + invNo + " .consignee_load_box .ship_party_state").html(ucons_display.State);
        $("#invoice_no_" + invNo + " .consignee_load_box .ship_party_post_code").html(ucons_display.PostCode);
        $("#invoice_no_" + invNo + " .consignee_load_box .ship_party_country").html(ucons_display.Country);
        $("#invoice_no_" + invNo + " .consignee_load_box .ship_party_phone").html(ucons_display.Phone);
    }
    // Load buyer data
    if (invoice.Buyer.length != 0) {
        var buyer_display = invoice.Buyer;
        var buyer_load_input = '';
        buyer_load_input = buyer_display.Name + " - " + buyer_display.Street1 + " - " + buyer_display.Street2 + " - " + buyer_display.City + " - " + buyer_display.State + " - " + buyer_display.PostCode;
        $("input.buyer_party").val(buyer_load_input);
        $("div.buyer_load_box").show();

        $("#invoice_no_" + invNo + " .buyer_load_box .ship_party_name").html(buyer_display.Name);
        $("#invoice_no_" + invNo + " .buyer_load_box .ship_party_street1").html(buyer_display.Street1);
        $("#invoice_no_" + invNo + " .buyer_load_box .ship_party_street2").html(buyer_display.Street2);
        $("#invoice_no_" + invNo + " .buyer_load_box .ship_party_city").html(buyer_display.City);
        $("#invoice_no_" + invNo + " .buyer_load_box .ship_party_state").html(buyer_display.State);
        $("#invoice_no_" + invNo + " .buyer_load_box .ship_party_post_code").html(buyer_display.PostCode);
        $("#invoice_no_" + invNo + " .buyer_load_box .ship_party_country").html(buyer_display.Country);
        $("#invoice_no_" + invNo + " .buyer_load_box .ship_party_phone").html(buyer_display.Phone);
    }
    $("#invoice_no_" + invNo + " .invoice_no").val(invoice.InvoiceNo);
    $(".entry_filing_type option[value=" + invoice.InvoiceType + "]").attr("selected", "selected");
    $("#ImporterId").val(invoice.Importer);
    $("#invoice_no_" + invNo + " .discount_currency").val(invoice.DiscountCurrency);
    $("#invoice_no_" + invNo + " .discount_amount").val(invoice.DiscountValue);
    $("#invoice_no_" + invNo + " .insurance_currency").val(invoice.InsuranceCurrency);
    $("#invoice_no_" + invNo + " .insurance").val(invoice.InsuranceCharges);
    $("#invoice_no_" + invNo + " .freight").val(invoice.Freight);
    $("#invoice_no_" + invNo + " .arrival_date").val(invoice.ArrivalDate);
    $("#invoice_no_" + invNo + " .total_units_shipped").val(invoice.TotalUnitsShipped);
    $("#invoice_no_" + invNo + " .delivery_terms option[value='" + invoice.DeliveryTerms + "']").attr("selected", "selected");

    if (invoice.RelatedParty == "Y") {
        $("#invoice_no_" + invNo + " input[name=related_parties]").filter("[value='Y']").attr("checked", "checked");
    } else {
        $("#invoice_no_" + invNo + " input[name=related_parties]").filter("[value='N']").attr("checked", false);

    }

    $("#invoice_no_" + invNo + " .units_of_measure option[value=" + invoice.UOM + "]").attr("selected", "selected");
    $("#invoice_no_" + invNo + " .country_of_export").val(invoice.CountryOfExport);
    $("#invoice_no_" + invNo + " .export_date").val(invoice.ExportDate);
    $("#invoice_no_" + invNo + " .vessel_name").val(invoice.VesselName);
    $("#invoice_no_" + invNo + " .vessel_flight_no").val(invoice.VesselNo);
    $("#invoice_no_" + invNo + " .port_lading").val(invoice.PortLading);
    $("#invoice_no_" + invNo + " .usc_location").val(invoice.USCLocation);
    $("#invoice_no_" + invNo + " .payment_by option[value=" + invoice.PaymentBy + "]").attr("selected", "selected");

    if (invoice.Insured == "Y") {
        $("#invoice_no_" + invNo + " input[name=insured]").filter("[value='Y']").attr("checked", "checked");
    } else {
        $("#invoice_no_" + invNo + " input[name=insured]").filter("[value='N']").attr("checked", false);

    }

    $("#invoice_no_" + invNo + " .release_port").val(invoice.ReleasePort);
    $("#invoice_no_" + invNo + " .invoice_date").val(invoice.InvoiceDate);
    $("#invoice_no_" + invNo + " .entry_no").val(invoice.EntryNo);
    $("#invoice_no_" + invNo + " .currency").val(invoice.Currency);
    $("#invoice_no_" + invNo + " .invoice_type option[value=" + invoice.TransType + "]").attr("selected", "selected");
    $("#invoice_no_" + invNo + " .payment_terms option[value=" + invoice.PaymentTerms + "]").attr("selected", "selected");
    $("#invoice_no_" + invNo + " .gross_weight").val(invoice.GrossWeight);
    $("#invoice_no_" + invNo + " .delivery_location").val(invoice.LocationCode);
    $("#invoice_no_" + invNo + " .manifest_description").val(invoice.BrokerProductDesc);
    $("#invoice_no_" + invNo + " .freight_to_border").val(invoice.Charges);
    $("#invoice_no_" + invNo + " .country_export").val(invoice.CountryOfExport);
    $("#invoice_no_" + invNo + " .units_shipped").val(invoice.TotalUnitsShipped);
    $("#invoice_no_" + invNo + " .freight_currency").val(invoice.FreightCurrency);
    $("#invoice_no_" + invNo + " .location_code").val(invoice.LocationCode);

    if ((invoice.ReferenceNumber != undefined) && (invoice.ReferenceNumber != null) && (invoice.ReferenceNumber.length > 0)) {
        if (invoice.ReferenceNumber.length == 1) {
            $("#invoice_no_" + invNo + " .ref_no").val(invoice.ReferenceNumber[0]);
            $("#invoice_no_" + invNo + " .ref_no").show();
            $('.refDisplayBox').hide();
        } else {
            $("#invoice_no_" + invNo + " .ref_no").hide();
            $('.refDisplayBox').show();

            var dropDown = $('.refDisplayBox')[0];
            dropDown.options.length = 0;

            for (var i = 0; i < invoice.ReferenceNumber.length; i++) {
                var referenceNumber = invoice.ReferenceNumber[i];
                dropDown.options[dropDown.options.length] = new Option(referenceNumber, referenceNumber);
            }
        }

    }
    if ((invoice.RelatedDoc != undefined) && (invoice.RelatedDoc != null) && (invoice.RelatedDoc.length > 0)) {
        if (invoice.RelatedDoc.length == 1) {
            $('.mrdDisplayBox').hide();
        } else {
            //$("#invoice_no_"+invNo+" .ref_no").hide();
            $('.mrdDisplayBox').show();

            var mrdDropDown = $('.mrdDisplayBox')[0];
            mrdDropDown.options.length = 0;

            for (var i = 0; i < invoice.RelatedDoc.length; i++) {
                var reldatedDoc = invoice.RelatedDoc[i];
                mrdDropDown.options[mrdDropDown.options.length] = new Option(invoice.RelatedDoc[i].Id + " - " + invoice.RelatedDoc[i].Number, invoice.RelatedDoc[i].Number);
            }
        }
    }
    if ((invoice.IT != undefined) && (invoice.IT != null) && (invoice.IT.length > 0)) {
        if (invoice.IT.length == 1) {
            $('.itDisplayBox').hide();
        } else {
            $('.itDisplayBox').show();

            var itDropDown = $('.itDisplayBox')[0];
            itDropDown.options.length = 0;

            for (var i = 0; i < invoice.IT.length; i++) {
                var itBox = invoice.IT[i];
                itDropDown.options[itDropDown.options.length] = new Option(invoice.IT[i].Number + " - " + invoice.IT[i].Date + " - " + invoice.IT[i].PortUnlading, invoice.IT[i].Number);
            }
        }
    }
    if ((invoice.BillLading != undefined) && (invoice.BillLading != null) && (invoice.BillLading.length > 0)) {
        if (invoice.BillLading.length == 1) {
            $('.bolDisplayBox').hide();
        }
        else {
            //$("#invoice_no_"+invNo+" .ref_no").hide();
            $('.bolDisplayBox').show();

            var bolDropDown = $('.bolDisplayBox')[0];
            bolDropDown.options.length = 0;

            for (var i = 0; i < invoice.BillLading.length; i++) {
                var bolBox = invoice.BillLading[i];
                bolDropDown.options[bolDropDown.options.length] = new Option(invoice.BillLading[i].BillLadingType + " - " + invoice.BillLading[i].BillLadingSCAC + " - " + invoice.BillLading[i].BillLadingQty + " - " + invoice.BillLading[i].BillLadingUOM, invoice.BillLading[i].BillLadingSCAC);
            }
        }

    }
    if ((invoice.ContainerNum != undefined) && (invoice.ContainerNum != null) && (invoice.ContainerNum.length > 0)) {
        if (invoice.ContainerNum.length == 1) {
            $('.conDisplayBox').hide();
        } else {
            $('.conDisplayBox').show();
            var conDropDown = $('.conDisplayBox')[0];
            conDropDown.options.length = 0;
            for (var i = 0; i < invoice.ContainerNum.length; i++) {
                var containerNumber = invoice.ContainerNum[i];
                conDropDown.options[conDropDown.options.length] = new Option(containerNumber, containerNumber);
            }
        }
    }

Open in new window


The conditionals at the bottom of the page LOAD data in to a SELECT box that is type multiple so I need to add each option for every line in the JSON.

Thanks again.
0
 
LVL 1

Author Comment

by:catonthecouchproductions
Comment Utility
I have a shot of the fields I am talking about

- set val in of input text
- set value of selected item in a select
- drop in all items in to a select type multiple (example: related documents)

Will the function you made be similar, judging by the fields posted and string format
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Browsers only know CSS so your awesome SASS code needs to be translated into normal CSS. Here I'll try to explain what you should aim for in order to take full advantage of SASS.
JavaScript has plenty of pieces of code people often just copy/paste from somewhere but never quite fully understand. Self-Executing functions are just one good example that I'll try to demystify here.
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now