How to dynamically set the title of a file.

How to dynamically set the title of a file.

ruleboy21ruleboy21 Posts: 14Questions: 3Answers: 0

I have an input field and a print button in a collection dropdown. The input field helps users to set their preferred title dynamically.

Since there are a couple of tables on the page, I was struggling to get the input field's value. But I managed to get it working with below code.

config.parent._collection[0].firstElementChild.value.trim();

Please is it how something like this should be handled or there is a better way?
Thanks.

Test Case: https://live.datatables.net/gidakera/1

The actual code is similar to this.

var table = new DataTable('#example', {
    layout: {
        topStart: {
            buttons: [
                {
                    extend: 'collection',
                    text: 'Export',
                    buttons: [
                        '<input type="text" maxlength="100" placeholder="Enter title">',
                        {
                            extend: 'print',
                            title: function (config, dt) {
                                return config.parent._collection[0].firstElementChild.value.trim();
                            }
                        }
                    ]
                }
            ]
        }
    }
});

This question has an accepted answers - jump to answer

Answers

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    That works well, nice job,

    Colin

  • allanallan Posts: 63,434Questions: 1Answers: 10,458 Site admin
    Answer ✓

    Rather than using the private variables (_collection), since it is possible that they might change between versions (although unlikely in this case I think), I'd be tempted to assign an id to the input and then query that directly:

    return $('#title').val().trim();
    

    Updated example here: https://live.datatables.net/geqeyizi/1/edit .

    Allan

  • ruleboy21ruleboy21 Posts: 14Questions: 3Answers: 0

    Thanks for the replies.

    @allan that is what I did initially but I wanted to avoid ids and classes so I can extract the collection into a custom button which can be used on multiple tables on the same page.

    With ids and classes it's hard to get the correct title related to the clicked button. That is why I wanted to selected the actual DOM element.

    But I guess I should rethink my approach.

    Thanks a lot.

  • ruleboy21ruleboy21 Posts: 14Questions: 3Answers: 0

    Please ignore my earlier comment. I tested @allan's answer, it works well.

    Thanks

  • allanallan Posts: 63,434Questions: 1Answers: 10,458 Site admin

    Awesome - thanks for the update. I'll look into a way via the API to address the button without needing to have a static / manual value like that.

    Allan

Sign In or Register to comment.