Javascript autofocus on ruby table elements
My program allows a user to click a button and then a table row gets up into the table via ajax. What I need is for the focus to be on the text field in that row ready for the user to add data into.
My ajax ruby code:
if( $('#effort_<%= @project_task.id %>').length == 0 )
$('#task_list').prepend('<tr><td><%= @project_task.project.project_number %> <%= @project_task.project.project_name %> - <%= @project_task.task_name %></td>' +
'<td><%= text_field :effort, :hours, :name => 'effort_' + @project_task.id.to_s, :id => 'effort_' + @project_task.id.to_s, :size => 20 %></td>' +
'<td><%= link_to image_tag('icons/delete.png'), "Delete", :method => :delete, :confirm => "Are you sure?", :remote => :true, :title => "delete row", :class => "delete" %></td></tr>' );
:autofocus => true
doesn't work.
My main problem is getting the autofocus to work on the LAST row that is added and also only on the rows that are ADDED. The table is filled with other rows that haven't been added, so when the user loads the screen and hasn't added anything the 开发者_开发百科autofocus shouldnt exist.
This is a hard one and I need to be pointed in the right direction.
Update
Generated html when a row is added: <tr>
<td>S006T - Project</td>
<td>
<input id="effort_5" type="text" size="20" name="effort_5">
</td>
<td>
<a class="delete" title="delete row" rel="nofollow" data-remote="true" data-method="delete" data-confirm="Are you sure?" href="Delete">
<img src="/images/icons/delete.png?1314715563" alt="Delete">
</a>
</td>
</tr>
Immediately after you prepend the new row to the list, just call jQuery focus() on the added element:
$('#effort_<%= @project_task.id.to_s %>').focus();
精彩评论