August 18, 2014 Brushed up the code example as it had some faulty quotes due to an error in the migration of the contents when I moved the blog some time ago.
25.03.2011 Fixed a bug in the DispForm code – thanks to Brian for noticing.
13.09.2010 Updated to support shared fields in the arrays – as requested by Larry.
This is a follow up on this article. You must read this article to get the basics before proceed with this one.
I will here give an example on how to use a multi select in stead of the single choice dropdown used in the previous article.
The only modification to the form from the previous , is the field “MySelect” which now should be changed to “Checkboxes (allow multiple selections)”.
The code for NewForm and EditForm should now be like this:
<!-- The jQuery version must be 1.6 or above --> <script type="text/javascript" src="/Scripts/jquery-1.10.2.min.js"></script> <script type="text/javascript"> var fields = init_fields_v2(); // Arrays of fields to show or hide var arrRed = ['ShowIfRed1','ShowIfRed2']; var arrBlue = ['ShowIfBlue1','ShowIfBlue2']; // Multiselect $(fields['MySelect']).find('input').each(function(i){ // On page load if(i==0){ // call this only once multiSelectdynamicDisplay($(this)); } // Add onclick $(this).click(function(){ multiSelectdynamicDisplay($(this)); }); }); function multiSelectdynamicDisplay(inp){ var objChecked = {}; var arrToHide = []; var arrToShow = []; var inpAll = inp.parents('td.ms-formbody:first').find('input'); $.each(inpAll,function(){ objChecked[$(this).next().text()] = $(this).prop('checked'); }); // Check each option if(objChecked['Red']){ arrToShow = arrToShow.concat(arrRed); }else if(!objChecked['Red']){ arrToHide = arrToHide.concat(arrRed); } if(objChecked['Blue']){ arrToShow = arrToShow.concat(arrBlue); }else if(!objChecked['Blue']){ arrToHide = arrToHide.concat(arrBlue); } if(objChecked['Yellow']){ //alert("No array defined for "Yellow""); }else if(!objChecked['Yellow']){ // Has no array defined } // Hide toggleArr(arrToHide,true); // Show toggleArr(arrToShow,false); } function toggleArr(arr,hide){ if(hide){ for(i=0;i<arr.length;i++){ $(fields[arr[i]]).hide(); } }else if(!hide){ for(i=0;i<arr.length;i++){ $(fields[arr[i]]).show(); } } } function init_fields_v2(){ var res = {}; $("td.ms-formbody").each(function(){ var myMatch = $(this).html().match(/FieldName="(.+)"\s+FieldInternalName="(.+)"\s+FieldType="(.+)"\s+/); if(myMatch!=null){ // Display name var disp = myMatch[1]; // FieldInternalName var fin = myMatch[2]; // FieldType var type = myMatch[3]; if(type=='SPFieldNote'){ if($(this).find('script').length>0){ type=type+"_HTML"; }else if($(this).find("div[id$='TextField_inplacerte']").length>0){ type=type+"_EHTML"; } } if(type==="SPFieldLookup"){ if($(this).find("input").length>0){ type=type+"_Input"; } } // HTML Calc if(type==='SPFieldCalculated' && $(this).text().match(/(<([^>]+)>)/ig)!==null){ $(this).html($(this).text()); } // Build object res[fin] = this.parentNode; $(res[fin]).attr('FieldDispName',disp); $(res[fin]).attr('FieldType',type); } }); return res; } </script>
The code for DispForm should now be like this:
<script type="text/javascript" src="/Scripts/jquery-1.10.2.min.js"></script> <script type="text/javascript"> var fields = init_fields_v2(); // Arrays of fields to show or hide var arrRed = ['Title','ShowIfRed1','ShowIfRed2']; var arrBlue = ['Title','ShowIfBlue1','ShowIfBlue2']; // Hide all onload var arrToHide = []; arrToHide = arrToHide.concat(arrRed,arrBlue); toggleArr(arrToHide,true); // Find the ones selected var c = $(fields['MySelect']).find('.ms-formbody').text().replace(/xA0/g,''); cSplit = c.split('; '); $.each(cSplit,function(idx,color){ dynamicDisplay($.trim(color)); }); function dynamicDisplay(color){ var arrToShow = []; if(color=='Red'){ arrToShow = arrToShow.concat(arrRed); } if(color=='Blue'){ arrToShow = arrToShow.concat(arrBlue); } if(color=='Yellow'){ // No array defined } // Show toggleArr(arrToShow,false); } function toggleArr(arr,hide){ if(hide){ for(i=0;i<arr.length;i++){ $(fields[arr[i]]).hide(); } }else if(!hide){ for(i=0;i<arr.length;i++){ $(fields[arr[i]]).show(); } } } function init_fields_v2(){ var res = {}; $("td.ms-formbody").each(function(){ var myMatch = $(this).html().match(/FieldName="(.+)"\s+FieldInternalName="(.+)"\s+FieldType="(.+)"\s+/); if(myMatch!=null){ // Display name var disp = myMatch[1]; // FieldInternalName var fin = myMatch[2]; // FieldType var type = myMatch[3]; if(type=='SPFieldNote'){ if($(this).find('script').length>0){ type=type+"_HTML"; }else if($(this).find("div[id$='TextField_inplacerte']").length>0){ type=type+"_EHTML"; } } if(type==="SPFieldLookup"){ if($(this).find("input").length>0){ type=type+"_Input"; } } // HTML Calc if(type==='SPFieldCalculated' && $(this).text().match(/(<([^>]+)>)/ig)!==null){ $(this).html($(this).text()); } // Build object res[fin] = this.parentNode; $(res[fin]).attr('FieldDispName',disp); $(res[fin]).attr('FieldType',type); } }); return res; } </script>
This article is, as mentioned above, a follow up on anther article. Read the previous article to get the basics.
Ask if anything is unclear.
Regards
Alexander
Hi Alex,
thanks for your help, i really enjoy your blog 😀
Best Regards, Mark
Hey Alex,
How are you?
Well I tried to implement that solution with a bit difference, I inlcluded more checkboxes fiels with only one option loading 5 fields each option and my code for New Form and Edit stays like that:
But something is wrong with my Display view, I included the following code but is not working, do you have any idea what is happening?
Please consider that my second code ends at line 79
Hey that happens if I have one multiselect field like MySelect field
What happens if I would like to add more than on multicheckbox select field?
I tried that calling the function Multiselect in this way:
So when I select one item from first field it expand but if I select other option from the other field the first one collapse
What I need to do to fix that?
I tried to do the following:
I tried to state the 2 fields in the same function but he only loads the second:”Dude”, and I don´t know why
Thanks
Renan
Sorry for not replying, it slipped by me due to a massive load of comments… Have you figured it out or do you still need help?
Alexander
Hey Alexander, Hope all is well. I was playing with this code and found something that slipped by me. I cant seem to figure out how to get it to work. The logic is shared fields in multiple arrarys. If in 2 of my 3 options I want the “Title” field to display (for both opt 2 and opt 3), it will only display for the last optiopn (opt 3). Is there a way to share a field across multiple arrays with this functionality?
I also just reread and found this is setup foir checkboxes. I am using radio buttons. I dont believe it should cause a difference. Only one selected as opposed to multiple selected.
Quick logic question. In my multipel select field I have 5 options. I want to show/hide field if 2 or more options are selected. I dont care which two. To aid with this I created a calculated field that return one fo 2 values
Low – one selected
High – 2 or more selected
Is there a way to make this work. I beleieve the calculated field wont have the new value until post, so is there a way to count number of selections instead of a specific selection?
Hi,
Sorry for the late reply, but her is a solution if the problem is still there:
The multi choice field has a FieldInternalName of “MySelect”.
Alexander
I have a list that I want to combine this code and the dropdown code on. I have a dropdown that I am using your code with to show/hide particular fields. But at the end of the form I have a Yes/No checkbox where I want to show a couple more additional fields if its checked ‘Yes’. Any way to do this?
Hi,
Doing this with a yes/no field requires some modifications. This is how to get the “on of off” property:
To have this work you will have to call the code on page load tho handle “selecting no” if the checkbox is initially unchecked.
Alexander
Forgot to add that it is a single checkbox. A check inside equals a ‘Yes’ and no check equals ‘No’
Hey A, Good day.
Hope all is well. I have an inquiry. I am looking for a way to show/hide a field based on a numerical value. More like a percentage. if field A/ field B is greater than 25%. Is there a way to do this? Can I divide one field by another in the function and use the result to hide/show field?
this is what i have worked up. I get an error onblur.
I tried adding you getFieldValue from another script. wrapped it in a function, then thought i could fire the function on blur. thats when the fields would be populated and I could divide. Hoping once I can get this value I can show/hide field based on return.
Hi,
Maybe I’m missing something in the code, but the variable “myNumVal” in line 14 is not defined. I guess you would have to include a call to getvalues() like this:
var myNumvVal = getvalues();
alert(myNumVal);
Alexander
Line 14 is suppose to be the result of (myNumAValue / myNumBValue). So maybe I am lost. I can’t seem to figure out how divide these to getFieldvalue numbers.
So Line 2 and 3 are suppose to grab these numbers. how can I calculate a percentage between those 2 numbers
Okay I am getting a little closer. I have stripped down my code as much as I can. In this function I can fire an alert on the field blur, but when i try to fire your getFieldValues function it errors out
Like this:
There is no need to use the getFieldValue to pull from a simple input field.
Alexander
You are my hero. Thanks a million. One small question. The blur function works perfectly on the NewForm. How should this be handled on the EditForm. Now the values are already populated, I need to check this in the blur function and on doc load, right?
Yes, that’s right.
Alexander
Hi Alexander,
First of all, awesome code!
I have two questions regarding code for DispForm.
1. I was trying your code and I noticed when I select both blue and red, on display form, I only see ‘ShowIfBlue1’ and ‘ShowIfBlue2′. Is there any fix for this?
2. On if(color==’Red’) line, if my value selection has space (i.e. Red Ball), how would you rewrite the code? I tried if(color==’Red Ball’), and it didn’t work.
Thank you!
Hi,
Both issues are fixed in the code – thanks for noticing!
Alexander
Thank you so much for fixing the code! You saved my day sir!
Hi. I’m always worried that I’m either repeating a question or I just sound dim, so sorry if either apply.
I have implemeneted the script successfully using a blank custom list in WSS3.0 copying the sample in every way and it works a charm. However, when I try to implement it into an existing form with many more fields it dowsn’t do anything. I have a support system and I want to create a choice selection of either “collect” or “onsite” (or both). By selecting them I want the newform.aspx to show / hide a number of reqired fields as per the selection.
Can you please take at look at my code and see if there is something that is clearly a mistake?
I appreciate any guidance you can offer
Hi,
Sorry for the late reply. Do you still have trouble or have you figured it out?
Alexander
Hi there. I moved away from the idea as I was getting nowhere. However, I’m still no further forward if you can help and I’d love to use it.
Thanks
Hi,
Sorry again for the delay.
You are missing a single quote around this fieldname: “Date_x0020_Onsite_x0020_Schedule” in the array “arrOnsite”.
Alexander
Thanks Alexander. As soon as I get chance I’ll implement it and post how I get on. My fingers are crossed 🙂
I really appreciate the help, thanks.
Richard
Hi Alexander,
any chance to have it customized for SHP 2010?
Thanks so much in advance
Joanna
Hi,
Have you tested it? I’m fairly sure it will work without modification.
Alexander
Hello,
I tried using this code and I can’t get it to work…nothing happen…Please help…
fields = init_fields();
//arrays of fields to show or hide
var arrHOLgl = [‘HO_x0020_Legal’,’HO_x0020_Legal_x0020_Notes’]
var arrCCLgl = [‘CCA_x0020_Legal’,’CCA_x0020_Legal_x0020_Notes’]
var arrCCDco = [‘CCA_x0020_DCO’,’CCA_x0020_DCO_x0020_Notes’]
// Multiselect
$(fields[‘PrelimAssignTo’]).find(‘input’).each(function(i){
// On page load
if(i==0){ // call this only once
MultiSelectdynamicDisplay($(this));
}
// Add onclick
$(this).click(function(){
MultiSelectdynamicDisplay($(this));
});
});
function MultiSelectdynamicDisplay(inp){
var objChecked = {};
var arrToHide = [];
var arrToShow = [];
var inpAll = inp.parents(‘td.ms-formbody:first’).find(‘input’);
$.each(inpAll,function(){
objChecked[$(this).next().text()] = $(this).attr(‘checked’);
});
// Check each option
if(objChecked[‘HO Legal’]){
arrToShow = arrToShow.concat(arrHOLgl);
}else if(!objChecked[‘HO Legal’]){
arrToHide = arrToHide.concat(arrHOLgl);
}
// Check each option
if(objChecked[‘CCA Legal’]){
arrToShow = arrToShow.concat(arrCCLgl);
}else if(!objChecked[‘CCA Legal’]){
arrToHide = arrToHide.concat(arrCCLgl);
}
// Check each option
if(objChecked[‘CCA DCO’]){
arrToShow = arrToShow.concat(arrCCDco);
}else if(!objChecked[‘CCA DCO’]){
arrToHide = arrToHide.concat(arrCCDco);
}
// Hide
toggleArr(arrToHide,true);
// Show
toggleArr(arrToShow,false);
}
function toggleArr(arr,hide){
if(hide){
for(i=0;i<arr.length;i++){
$(fields[arr[i]]).hide();
}
}else if(!hide){
for(i=0;i<arr.length;i++){
$(fields[arr[i]]).show();
}
}
}
function init_fields(){
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;
}
Hi Alexander,
I have a bit of an issue I was hoping you’d be able to help me with, if you’re still looking over these comments and open to explaining.
I am using SP 2010 and have been able to get jQuery to work, including the alert message, but once I paste in the code, the alert does not show anymore and I am at a loss. I placed the CEWP below the list and followed all the steps (including keeping the exact same column names as your example), but I can’t seem to get it to run properly.
I notice a lot of the other comments had the same problem at first, and it was due to improperly linking the jQuery document, but it seems to me that the functions are not even running. They show up in the page’s source code, but nothing kicks off. Do you have any idea why? Or how I can troubleshoot this?
Thanks a million for your time and attention.
Send me the code you are using, and I’ll take a look. Have you tried using the developer console? Hit F12 and look at the console.
You find my email in the “About me” tab in the top of the page.
Alexander
Hi,
I have updated the code example – it had some faulty quotes due to an error when I moved the contents of my blog some time ago.
Alexander