How do I find how many options there are for a select field?

How do I find how many options there are for a select field?

AlchetecAlchetec Posts: 14Questions: 5Answers: 0

I have the following field defined How do I get the number of options for the select? I'd like to hide the field if there is only 1.

$(document).ready(function() {
    var editor = new $.fn.dataTable.Editor( {
        ajax: 'php/PermissionToEnter.php',
        table: '#PermissionToEnter',
        fields: [
            {
                "label": "Unit",
                "name": "PermissionToEnter.unit",
                "type": "select2",
                "opts": {
                    theme: "classic"
                }
            },
.
.
.

Thanks!

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,519Questions: 1Answers: 10,473 Site admin
    edited February 2016 Answer ✓

    There isn't an API built into Editor for that - however, it is quite possible with a little jQuery to get the number of options:

    var field = editor.field( 'PermissionToEnter.unit' );
    
    if ( $('select > option', field.node().length < 2 ) {
      field.hide();
    }
    else {
      field.show();
    }
    

    Allan

    edit I've just realised you are using select2. This may or may not work in that case - I'm not 100% certain what select2 does with the select element.

  • AlchetecAlchetec Posts: 14Questions: 5Answers: 0

    The following worked:

    editor.one( 'open', function ( e, type ) {
        var field = editor.field( 'PermissionToEnter.unit' );
        
        if ( $('select > option', field.node()).length < 2 ) {
            field.hide();
        }
    } );
    
    

    a parenthesis was missing after field.nide :)

    Thanks again!!!

This discussion has been closed.