3

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 :)

jabez
  • 896
  • 1
  • 9
  • 22
  • It depends on from which function you are calling `$("#task").editable({ ...})` and how you are invoking *that* function. – techfoobar Jul 21 '13 at 18:01
  • Could you please be more specific? – jabez Jul 21 '13 at 18:04
  • For ex: if you are calling `$("#task").editable({ ...})` from inside the jQuery click handler of an element, `this` will be that element. If you are doing it from `$(document).ready()`, `this` will point to the document object and so on.. – techfoobar Jul 21 '13 at 18:06
  • the editable function is inside of `$(document).ready()` and how should I call `this` from inside the `editable` function to target the element I want? – jabez Jul 21 '13 at 18:13

1 Answers1

5

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'
});
karim79
  • 339,989
  • 67
  • 413
  • 406