I'm trying to get the class of the parent element of the currently focussed input. All the inputs have a class of .edit (that JEditable binds to). The parent class states which controller, field and id are used in the database update (I'm using Codeigniter with JQuery Ajax).
Here's my current code:
var basepath;
$(document).ready(function() {
basepath = "/mm/";
jedit();
});
function jedit() {
$('#container').live({
click: function() {
$('.edit').focus(function() {
var attributes = $(this).closest('tr').attr('class');
});
var splitResult = attributes.split("-");
var controller = splitResult[0];
var field = splitResult[1];
var id = splitResult[2];
$('.edit').editable(basepath+controller+'/edit/'+field+'/'+id,{
indicator:'<img src="'+basepath+'images/throbber.gif">'
});
}
});
}
Currently I get attributes is not defined
in the firebug console. I think this is because until the text to edit is clicked on, the input doesn't exist (so there is no focus). I've tried an if else
along the lines of:
if($('.edit input').length != 0) {
var attributes = $('.edit').closest('tr').attr('class');
} else {
var attributes = 'some nul thing here';
}
But that just always evaluates to false.
Any ideas or suggestions about how to get the parent class of the active .edit class, will be greatly appreciated.
Thanks!
The problem is you're declaring attributes
inside that .focus()
handler only (so it won't be available in the higher click
scope.
Instead, it should be defined in the scope you want to use it, the set it in that event handler, like this:
var attributes;
$('.edit').focus(function() {
attributes = $(this).closest('tr').attr('class');
});
However, in your case you'll want to use this data when the focus happens, overall looking like this:
function jedit() {
$('#container').delegate('.edit', 'focus', function() {
var result = $(this).closest('tr').attr('class').split("-"),
controller = result[0],
field = result[1],
id = result[2];
$(this).editable(basepath+controller+'/edit/'+field+'/'+id,{
indicator:'<img src="'+basepath+'images/throbber.gif">'
});
});
}
Also, as an aside, unless the class
is useful for other reasons, e.g. styling...consider using a data-
attribute specifically for data, rather than the browser trying to find/apply a CSS class here.