techie_28 techie_28 - 1 year ago 44
Javascript Question

Can not access element attributes after passing the reference jQuery

I have a HTML grid which has variable number of rows which has a datepicker in first column & an HTML button in 3rd column.

I need to get the reference of button & pass it around in functions(may be more then once) to call its click or access its attribute at various places.

var myButton = $(this).parents('tr').find('input[type=button]'); // accesing the button in a function

further I am passing this variable in an object to another JS function doSomething, { 'btnRef': myButton[0] }, condition);

Inside the doSmething function I am saving this reference in a global JS object

unsavedObj['btnRef'] = arguments[0]['btnRef']; // I also tried jQuery(arguments[0]['btnRef'])

Problem occurs after I try to access an attribute via the global object

unsavedObj['btnRef'] // shows as undefined in console.

I can access attributes etc correctly inside the function where var myButton is getting the value also
returns the right result as well.
Is this the problem due to context?.

Sample code:

//this is the datepicker handler which fires on select of a date.

onSelect: function(d,i) {
var condition = false;
var myButton = $(this).closest('tr').find('input[type=button]');
var btnRel = myButton.attr('rel');
//some other vars

myButton.prop("disabled", false); //this works fine

if(changedFor !=''){
if(changedFor == btnRel){
condition = (changedFor == btnRel);
},{'btnRef':myButton},condition);//passing to the function doSomething

//doSomething function.
function doSomething(){
var thisObj = jQuery(this)
}else{{ //this is a bootstrap dialogbox
var $content = "Are you sure?";
return '<div>' + $content + '</div>';
closable: false,
buttons: [{
cssClass: 'btn',
action: function(dialogItself){
unsavedObj['btnRef'] = arguments[0]['btnRef'];
unsavedObj['context'] = thisObj;
changedFor = unsavedObj['btnRef'].attr('rel'); //does not work
unsavedObj['btnRef'].click(); //does not work
action: function(dialogItself){

Im sorry for the poor formatting.


Answer Source

Sorry this problem was happening due to the limitation of closures to access the arguments object of outer function & here{..'s button definition was actually a closure. It was resolved by creating a copy of arguments.

Thanks all.