3

I am using CSR against two columns, both of which I need to hide from the list view.

I have used this example to successfully hide one:

function hideFields(ctx) 
{ 
var cell = $("div [name='myField']").closest('th'); 
var cellIndex = cell[0].cellIndex + 1; 

$('td:nth-child(' + cellIndex + ')').hide(); 
$('th:nth-child(' + cellIndex + ')').hide(); 
}

but I also need to hide another column and am struggling to do so - I've tried writing a separate function with new variable names but this doesn't work. Can I add a further column into the existing hideFields function ?

1
  • hi, can you not apply them the same class- then hide the elements of this class?
    – ova
    Sep 5, 2016 at 12:04

3 Answers 3

5

Try this one, you just need to replace the values in the array in line 2:

OnPostRender: function(ctx) {
    ["col1", "col2"].forEach(function(name) {
        var header = document.querySelectorAll("[displayname=" + name + "]")[0].parentNode;
        var index = [].slice.call(header.parentNode.children).indexOf(header) + 1;
        header.style.display = "none";
        for (var i = 0, cells = document.querySelectorAll("td:nth-child(" + index + ")"); i < cells.length; i++) {
            cells[i].style.display = "none";
        }
    });
}

(jQuery is not necessary for this script)

1
  • Solved my problems. Thanks! If you have empty spaces or special characters in you display names just add an apostrophe like this: "[displayname='" + name + "']"
    – lex
    Jul 4, 2017 at 13:51
1

Our farm didn't like the Vanilla JS of Daniel's answer so I ported it over to jQuery

["col1", "col2"].forEach(function(name) {   
        var header = jQuery("[displayname='" + name + "']").parent();

        var siblings = header.parent().children();
        var index = siblings.index(header) + 1;

        header.hide();

        jQuery("td:nth-child(" + index + ")").hide();

    });
0

I believe that both answers are useful and work well. The only remark that I would like to review in both codes is to avoid using "displayname" from DOM. Using the "name" selector is much better. It will help to avoid encoding mistakes and matching wrong field name, especially if you using non-latin international names for your fields. For expamle: var header = document.querySelectorAll("[name=" + name + "]")[0].parentNode; for Daniel's code and var header = jQuery("[name='" + name + "']").parent(); for the example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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