Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I have a SharePoint NewForm.aspx with some custom javascript/jquery to perform various tasks:

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
//?PageView=Shared&ToolPaneView=2
if(typeof jQuery=="undefined"){
    var jQPath="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/"; 
    document.write("<script src='",jQPath,"jquery.min.js' type='text/javascript'><\/script>");
}
</script>

<!--<script src="/sites/policies/jquery/HeadingsFromjQuery.js" type="text/javascript"></script>
<script src="/sites/policies/jquery/jquery.SPServices-2013.01.js" type="text/javascript"></script>
<script src="/sites/policies/jQuery/spcd.js" type="text/javascript"></script> -->
<script type="text/javascript">

/* 
 * Prepopulate form fields in SharePoint 
 * Copyright (c) 2008 Paul Grenier (endusersharepoint.com now nothingbutsharepoint.com) 
 * Licensed under the MIT (MIT-LICENSE.txt) 
 * Updated for 2010 by Brendan Horner for nothingbutsharepoint.com 
 */
(function(){ 
 var params = window.location.search.substring(1).split("&"), 
  kv = {}, 
  opts, 
  sp=/%20|\+/g, 
  datetime=/([1-9]|0[1-9]|1[012])[\-\/.]([1-9]|0[1-9]|[12][0-9]|3[01])[\-\/.](19|20)\d\d\s([0-1][0-2]|[0-9]):([0-9]{2})\s(A|P)M/i, 
  date=/([1-9]|0[1-9]|1[012])[\-\/.]([1-9]|0[1-9]|[12][0-9]|3[01])[\-\/.](19|20)\d\d/, 
  clean = function(str){ 
   return str.replace(sp," "); 
  }, 
  getKv = function(){ 
   $.each(params,function(i,e){ 
    var p=e.split("="); 
    kv[p[0]]=decodeURIComponent(p[1]); 
   }); 
   return kv; 
  }; 
 jQuery.prepop = function(){ 
  $.each(getKv(),function(k,v){  
   k=clean(k); 
   v=clean(v); 
   var f=$("[title='"+k+"']"), 
    job; 
   if (f.length>0){ 
    if (f[0].type=="text"){job=10;} //text 
    if (f[0].type=="checkbox"){job=20;} //checkbox 
    if (f[0].type=="select-one"&&f[0].tagName=="SELECT"){job=10;} //choice dropdown and non-IE lookup 
    if (f[0].tagName=="TEXTAREA"){job=10;} //Multi-lines of text 
    if (f[0].type=="text"&&f[0].opt=="_Select"){job=70;} //IE lookup with evil img and hidden input 
    if (v.match(date)){job=40;} //date 
    if (v.match(datetime)){job=50;} //datetime 
   } 
   if (f.length===0){  
    var elm = $("nobr:contains('"+k+"')"); 
    if (elm.length>0){ 
     elm = elm.closest("td").next()[0]; 
     var s1 = $(elm).find("select:first"), 
      s2 = $(elm).find("select:last"), 
      p1 = $(elm).find("textarea[title='People Picker']"), 
      p2 = $(elm).find("div[title='People Picker']"), 
      r1 = $(elm).find("span[title='"+v+"']"), 
      vals = v.split(","), 
      r2 = $(elm).find("span[title='"+vals[0]+"']"); 
     if (s1.length>0){job=80;} //multi-select 
     if (p1.length>0){job=90;} //people picker 
     if (r1.length>0||r2.length>0){job=30;} //radio button single select or checkbox list 
    } 
   } 
   switch (job){ 
   case 10: 
    if (v.substring(0,1)=="@"){ 
     opts = f[0].options; 
     $.each(opts,function(i,e){ 
      if (opts[i].value==v.substring(1)){f[0].selectedIndex=i;} 
     }); 
    }else{ 
     f.val(v); 
    } 
    break; 
   case 20: 
    if (v.toUpperCase()=="TRUE"||v=="1"){f[0].checked=true;} 
    if (v.toUpperCase()=="FALSE"||v=="0"){f[0].checked=false;} 
    break; 
   case 30: 
    $.each(vals, function(i,e){ 
     var V=TrimSpaces(e); //TrimSpaces is a function in core.js of SharePoint 2010 
     $.each($(elm).find("span.ms-RadioText").find("label"),function(i,e){ 
      if($(e).text()==V){ 
       $(e).prev().attr('checked',true); 
      } 
     }); 
    }); 
    break; 
   case 40: 
    v=v.replace(/[\-\/.]/g,"/"); 
    f.val(v); 
    break; 
   case 50: 
    var dt=v.split(" "), 
     d=dt[0].replace(/[\-\/.]/g,"/"), 
     t=dt[1], 
     hm=t.split(":"), 
     hh=hm[0].replace(/^0/,""), 
     mm=hm[1], 
     ap=dt[2].toUpperCase(); 
    f.val(d); 
    mm=5*Math.round(mm/5); 
    f.parent("td").siblings("td.ms-dttimeinput") 
     .find("select:first").val(hh+" "+ap) 
     .parent("td").find("select:last").val(mm);   
    break; 
   case 70: 
    fArr = f.attr('choices').split('|');  
    if (v.substring(0,1)=="@"){ 
     for (i=1;i<fArr.length;i=i+2){ 
      if(fArr[i] == v.substring(1)){  
       f.val(fArr[i-1]); 
       $('input[id="'+f.attr("optHid")+'"]').val(fArr[i]); 
      } 
     } 
     f.blur(); 
    }else{ 
     f.val(v); 
     for (i=0;i<fArr.length;i=i+2){ 
      if(fArr[i] == v){  
      $('input[id="'+f.attr("optHid")+'"]').val(fArr[i+1]); 
      } 
     } 
     f.blur(); 
    } 
    break; 
   case 80: 
    opts = s1[0].options; 
    var s1hiddenInput = s1.parents('span').find('input[type="hidden"]').first(); 
    var s1hiddenVal=""; 
    $.each(vals,function(i,e){ 
     var V=e; 
     $.each(opts,function(i,e){ 
      if (opts[i].text==V){ 
       s2.append("<option value='"+opts[i].value+"'>"+V+"</option>"); 
       s1hiddenVal+=opts[i].value+"|t"+V+"|t"; 
      } 
      if (V.substring(0,1)=="@"){ 
       if (opts[i].value==V.substring(1)){ 
        s2.append("<option value='"+V+"'>"+opts[i].text+"</option>"); 
        s1hiddenVal+=opts[i].value+"|t"+V+"|t"; 
       } 
      } 
     }); 
    }); 
    s1hiddenInput.attr('value',s1hiddenVal); 
    break; 
   case 90: 
    var p=vals.join(";"); 
    p1.val(p); 
    p2.html(p); 
    break; 
   } 
  }); 
 }; 
})(); 
$(window).load(function(){ 
 $.prepop(); 
}); 


<!-- SECTION 2.0: SHOW WORK AREA DETAILS-->

WAfields = init_fieldsWA();
// Arrays of fields to show or hide
var arrWA1 = ['ServiceOther'];
var arrWA2 = ['ServiceCEA'];
var arrWA3 = ['ServiceDHIS'];
var arrWA4 = ['ServiceDCHSBankStaff'];
var arrWA5 = ['ServiceHPES'];
var arrWA6 = ['ServiceHWI'];
var arrWA7 = ['ServiceHROD'];
var arrWA8 = ['ServiceFIP'];
var arrWA9 = ['ServiceICBS'];
var arrWA10 = ['ServicePOE'];
var arrWA11 = ['ServicePCO'];
var arrWA12 = ['ServiceQIG'];
var arrWA13 = ['ServiceStrategy'];

// Hide all onload
var arrToHideWA = [];
arrToHideWA = arrToHideWA.concat(arrWA1,arrWA2,arrWA3,arrWA4,arrWA5,arrWA6,arrWA7,arrWA8,arrWA9,arrWA10,arrWA11,arrWA12,arrWA13);
toggleArrWA(arrToHideWA,true);

// Onchange
$(WAfields['WorkArea']).find('select').change(function(){
var c = $(this).find('option:selected').text();
               dynamicDisplayWA(c);
});


// Onload
var c = $(WAfields['WorkArea']).find('option:selected').text();
dynamicDisplayWA(c);

function dynamicDisplayWA(workarea){
// Hide all initially
toggleArrWA(arrToHideWA,true);
               if(workarea=='Other'){
                              toggleArrWA(arrWA1,false);
               }
               else if(workarea=='Chief Executive/Administration'){
                              toggleArrWA(arrWA2,false);
               }
               else if(workarea=='DHIS'){
                              toggleArrWA(arrWA3,false);
        }
               else if(workarea=='DCHS Bank Staff'){
                              toggleArrWA(arrWA4,false);
         }
               else if(workarea=='Health Wellbeing & Inclusion'){
                              toggleArrWA(arrWA5,false);
         }
              else if(workarea=='Human Resources/Organisational Development'){
                              toggleArrWA(arrWA6,false);
         }
              else if(workarea=='Finance, Information & Performance'){
                              toggleArrWA(arrWA7,false);
         }
             else if(workarea=='Integrated Community Based Services'){
                              toggleArrWA(arrWA8,false);
         }
            else if(workarea=='People & Organisational Effectiveness'){
                              toggleArrWA(arrWA9,false);
         }
            else if(workarea=='Planned Care & Outpatients'){
                              toggleArrWA(arrWA10,false);
         }
            else if(workarea=='Quality & Integrated Governance'){
                              toggleArrWA(arrWA11,false);
         }
            else if(workarea=='Strategy'){
                              toggleArrWA(arrWA12,false);
         }
}


function toggleArrWA(arrWA,hide){
  if(hide){
    for(i=0;i<arrWA.length;i++){
      $(WAfields[arrWA[i]]).hide();
    }
  }else if(!hide){
    for(i=0;i<arrWA.length;i++){
      $(WAfields[arrWA[i]]).show();
    }
  }
}

function init_fieldsWA(){
var res = {};
$("td.ms-formbody").each(function(){
if($(this).html().indexOf('FieldInternalName="')<0) return;
var start = $(this).html().indexOf('FieldInternalName="')+19;
var stopp = $(this).html().indexOf('FieldType="')-7;
var nm = $(this).html().substring(start,stopp);
res[nm] = this.parentNode;
});
return res;
};

<!-- SECTION 2.0: SHOW PRACTICE DETAILS-->

PRAfields = init_fieldsPRA();
// Arrays of fields to show or hide
var arrPRA1 = ['WhichPractice'];
var arrPRA2 = ['PracticeLocation'];

// Hide all onload
var arrToHidePRA = [];
arrToHidePRA = arrToHidePRA.concat(arrPRA1,arrPRA2);
toggleArrPRA(arrToHidePRA,true);

// Onchange
$(PRAfields['Location']).find('select').change(function(){
var c = $(this).find('option:selected').text();
               dynamicDisplayPRA(c);
});


// Onload
var c = $(PRAfields['Location']).find('option:selected').text();
dynamicDisplayPRA(c);

function dynamicDisplayPRA(practice){
// Hide all initially
toggleArrPRA(arrToHidePRA,true);
               if(practice=='Other'){
                              toggleArrPRA(arrPRA2,false);
               }
               else if(practice=='GP Practice'){
                              toggleArrPRA(arrPRA1,false);
               }
}


function toggleArrPRA(arrPRA,hide){
  if(hide){
    for(i=0;i<arrPRA.length;i++){
      $(PRAfields[arrPRA[i]]).hide();
    }
  }else if(!hide){
    for(i=0;i<arrPRA.length;i++){
      $(PRAfields[arrPRA[i]]).show();
    }
  }
}

function init_fieldsPRA(){
var res = {};
$("td.ms-formbody").each(function(){
if($(this).html().indexOf('FieldInternalName="')<0) return;
var start = $(this).html().indexOf('FieldInternalName="')+19;
var stopp = $(this).html().indexOf('FieldType="')-7;
var nm = $(this).html().substring(start,stopp);
res[nm] = this.parentNode;
});
return res;
};

<!-- SECTION 3.0: SHOW HOW DATA TRANSFERED DETAILS-->

TRNfields = init_fieldsTRN();
// Arrays of fields to show or hide
var arrTRN1 = ['EmailAcc', 'HowDataSent'];
var arrTRN2 = ['PostMethod', 'PrivConf'];
var arrTRN3 = ['CovShtPrivConf', 'CallAhead', 'RecipientConf'];
var arrTRN4 = ['EncryptedCD', 'HowCDSent'];
var arrTRN5 = ['ITSystem'];
var arrTRN6 = ['ConsentText'];
var arrTRN7 = ['OtherInfo'];

// Hide all onload
var arrToHideTRN = [];
arrToHideTRN = arrToHideTRN.concat(arrTRN1,arrTRN2,arrTRN3,arrTRN4,arrTRN5,arrTRN6,arrTRN7);
toggleArrTRN(arrToHideTRN,true);

// Onchange
$(TRNfields['HowTransfer']).find('select').change(function(){
var c = $(this).find('option:selected').text();
               dynamicDisplayTRN(c);
});


// Onload
var c = $(TRNfields['HowTransfer']).find('option:selected').text();
dynamicDisplayTRN(c);

function dynamicDisplayTRN(transfer){
// Hide all initially
toggleArrTRN(arrToHideTRN,true);
               if(transfer=='Email'){
                              toggleArrTRN(arrTRN1,false);
               }
               else if(transfer=='Post'){
                              toggleArrTRN(arrTRN2,false);
               }
               else if(transfer=='Fax'){
                              toggleArrTRN(arrTRN3,false);
        }
               else if(transfer=='CD'){
                              toggleArrTRN(arrTRN4,false);
         }
               else if(transfer=='Within an IT system (e.g. through Oracle)'){
                              toggleArrTRN(arrTRN5,false);
         }
              else if(transfer=='SMS (Text) Message'){
                              toggleArrTRN(arrTRN6,false);
         }
              else if(transfer=='Other'){
                              toggleArrTRN(arrTRN7,false);
         }
}


function toggleArrTRN(arrTRN,hide){
  if(hide){
    for(i=0;i<arrTRN.length;i++){
      $(TRNfields[arrTRN[i]]).hide();
    }
  }else if(!hide){
    for(i=0;i<arrTRN.length;i++){
      $(TRNfields[arrTRN[i]]).show();
    }
  }
}

function init_fieldsTRN(){
var res = {};
$("td.ms-formbody").each(function(){
if($(this).html().indexOf('FieldInternalName="')<0) return;
var start = $(this).html().indexOf('FieldInternalName="')+19;
var stopp = $(this).html().indexOf('FieldType="')-7;
var nm = $(this).html().substring(start,stopp);
res[nm] = this.parentNode;
});
return res;
};


</script>

All the code works fine when the NewForm.aspx is opened normally and normally populated by the user. Now however, ive created a Ribbon Button which basically opens up the NewForm.aspx page and parses the values in the URL string into the blank FormField boxes. (Imagine opening a record and clicking a copy button to create a new item with the same values populated in the NewForm.asp FormFields) Again, this works with the code, but some of the FormFields on my form are hidden and only shown when certain values in certain dropdowns are chosen. This is where my problem lies...

Basically if the user clicks and chooses a value from the dropdown the javascript fires as expected and the hidden FormFields are shown, but when the values are parsed into the FormFields obviously there is no actual interaction on the FormField so the javascript doesnt function.

Simply, how can I force the Javascript functions to run without users re-selecting the dropdown values?

share|improve this question
    
My JavaScript is novice at best, so excuse me if this is a stupid question, but won't changing the value of a drop down with JavaScript still fire a change event? Or are you using a different event to show/hide the form fields? –  wjervis Jun 11 at 16:24

2 Answers 2

I think your question is how to fire events in JavaScript?

While this isn't really specific to SharePoint, you can refer to the StackOverflow question How to trigger event in JavaScript?

Or you can use jQuery's .trigger() function:

.trigger( eventType [, extraParameters ] )

Description: Execute all handlers and behaviors attached to the matched elements for the given event type.

The example provided there is:

$( "#foo" ).on( "click", function() {
    alert( $( this ).text() );
});

$( "#foo" ).trigger( "click" );
share|improve this answer

I think you're setting up your events after you initially populate your field values.

But things are a bit too complicated, Instead of relying on your listeners you can setup the hidden fields as well right? You can create functions and call those functions in the event handlers you set up.

function updateHiddenField(){
    //code here
}


//onchange of dropdown call updateHiddenField()
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.