Search code examples
jquerythisedit-in-place

$(this) not working x-editable


I'm trying to set up a dynamic retrieve of a pk and this selector is not working, here is my code:

#html file
<div id="{{task.id}}">
                <h3>
                    <a href="#" id="task">{{ task.task }}</a>
                </h3>
...
</div>

#js file
$("#task").editable({
    type: 'text',
    **pk:  $(this).closest('div').attr('id'),**
    url: '/update_task/' + pk + '/',
    title: 'Enter task',

});

this one is not working, but if I write:

pk:  $("#task").closest('div').attr('id')

will work, but is not convenient for me.

Thank you in advance :)


Solution

  • this refers to the options object, and not the jQuery object. If you have the one-off field from which you want to extract the primary key to send to the server, then I would simply do:

    var $task = $("#task");
    $task.editable({
        type: 'text',
        pk:  $task.attr("id"),
        url: '/update_task/' + pk + '/',
        title: 'Enter task',
    });
    

    If you are using a more generic selector, such as .someDiv and want the pk for each individual one, you can use the params option with a callback, which allows you to append/overwrite the data to be sent, depending on whether you pass an object or a function (function overwrites, see the docs):

    $(".someDiv").editable({
        type: 'text',
        pk:  0,
    
        // hooray, params takes a callback so
        // we can get the right context
        params: function (params) {
            var data = {};
            data.pk = $(this).closest("div").attr("id"),
            data.makesure = "You know that this will overwrite the original params object";
            data.soPut = "Everything you need into it before returning";
            return data;
        },
        url: '/update_task/' + pk + '/',
        title: 'Enter task'
    });
    

    p.s. pk seems to accept a function too, so I guess you can do this, but I'm in no position to test right now:

    $("#task").editable({
        type: 'text',
        pk:  function () {
            return $(this).closest("div").attr("id");
        },
        url: '/update_task/' + pk + '/',
        title: 'Enter task'
    });