function dynamicallyFilterSubGrid() {

    //RelatedCars : is name of subgrid given on Form. 
    var objSubGrid = document.getElementById("RelatedCars");

    //CRM loads subgrid after form is loaded.. so when we are adding script on form load.. need to wait unitil subgrid is loaded. 
    // thats why adding delay..
    if (objSubGrid == null || objSubGrid.readyState != "complete") {
        setTimeout(dynamicallyFilterSubGrid, 2000);
        return;
    }

    else {
        //when subgrid is loaded, get category value
        var category = Xrm.Page.getAttribute('new_category').getValue();

        //Create FetchXML for sub grid to filter records based on category
        var FetchXml = "<fetch distinct='false' mapping='logical' output-format='xml-platform' version='1.0'>" +
                            "<entity name='new_car'>" +
                                "<attribute name='new_name'/>" +
                                "<attribute name='createdon'/>" +
                                "<attribute name='new_year'/>" +
                                "<attribute name='new_id'/>" +
                                "<attribute name='new_category'/>" +
                                "<attribute name='new_carid'/>" +
                                "<order descending='false' attribute='new_name'/>" +
                                "<filter type='and'>" +
                                    "<condition attribute='statecode' value='0' operator='eq'/>" +
                                    "<condition attribute='new_category' value='" + category + "' operator='eq'/>" +
                                 "</filter>" +
                            "</entity>" +
                        "</fetch>";

        // Layout of subgrid.
        var LayoutXml = "<grid name='resultset' object='8' jump='new_name' select='1' preview='1' icon='1'>" +
                            " <row name='result' id='new_boat'>" +
                                    "<cell name='new_id' width='100' />" +
                                    "<cell name='new_name' width='200' />" +
                                    "<cell name='new_category' width='200' />" +
                                    "<cell name='new_year' width='100' />" +
                                    "<cell name='createdon' width='100' />" +
                                "</row>" +
                         "</grid>";

        //apply layout and filtered fetchXML
        objSubGrid.control.SetParameter("layoutXml", LayoutXml);
        objSubGrid.control.SetParameter("fetchXml", FetchXml);

        //Refresh grid to show filtered records only. 
        objSubGrid.control.Refresh();

    }
}