DataGrid cell events

Jul 4, 2011 at 9:57 PM
Edited Jul 4, 2011 at 9:58 PM

Hi,

I am using the datagrid and what I want to do is place the jQuery UI autocomplete on a cell in the grid to help the users choose an item.  However when I click "Insert" and it adds a new row the cell does not have the autocomplete on it even though I have set it up in the document.ready event.  I essentially put an attribute on the cell called "ac" and set the text to my backend action which will populate the list.  I then put this in the document ready function:

$.each($('input[ac]'), function

() {

 $(this).autocomplete({

source: $(this).attr('ac'

)

 

});

});

 

This works on all existing items in the grid but not new ones I insert.  Is there an option in the DataGrid that I can fire a post event after an insert?

Cheers,

Craig

 

Coordinator
Jul 5, 2011 at 10:21 AM
Edited Jul 5, 2011 at 11:10 AM

There is no need for such event: you can put javascript code directly in the row template. This code is executed when the row is attached to the grid, and then it is destroyed to avoid multiple executions.

Moreover you can use the PrefixedId helper to get the id of an element rendered by the Mvc engine.  So, suppose your input field to be turned into an autocomplete is named 'MyInput' , you can write something like :

 

<script language='javascript' type='text/javascript'>
$('#@item.PrefixedId(m => MyInput)').autocomplete(......);
</script>

 

This is acceptable if there is just one input field per row you would like to transform. If there are several you will put too much javascript code in the row template.

in this case it is better to call just a javascript function that initialize the row:

 

<script language='javascript' type='text/javascript'>
initializeRow('@item.PrefixedId(string.Empty)');
</script>

 

 

 

You just pass the prefix of all names to the initialize function. Then say your function definition is: initializeRow(prefix){..................}. The above code is executed once for each row when the row is attached to the grid. ATTENTION it is executed also for the rows that are already in the grid when the grid is created, not only with the rows created with the add button!

Then you can refer to the id of the previous input field as prefix+'_MyInput', to the overall container of the whole row in edit mode: prefix+"_Edit_Container". Thus you can add auto complete to all input fileds in the row with your attribute with:

 

$('#'+prefix+"_Edit_Container input[ac]").autocomplete(......);

The postfix for the Display mode of the row is: "_Display_Container".

See also here

Jul 5, 2011 at 10:53 PM

Thanks.  That worked a treat!