Reputation: 15002
I try to send a form and delete the an table row when click the submit button.
the delete row function I did it in Coffee Script way,and "delete the table row" works.
However,the submit form function didn't work.
But if I remove the Coffee Script, the submit form works again.
Coffee Script
jQuery ->
$("#rf_tbl").on "click", "input[type=\"submit\"]", (e) ->
$(this).closest("tr").remove()
View
= form_tag kill_running_task_remote_focus_path, :method => :get, remote: true do
%table#rf_tbl.table.table-condensed.table-striped
%tr
%th User
%th Camera IP
%th Created Time
%th PID
%th Control
- @running_tasks.each do |running_task|
%tr{:id => "#{running_task[:pid]}"}
- running_task.each do |key, value|
%td
= value
%td
= hidden_field_tag :task, running_task[:pid]
= submit_tag "Kill This Task" ,:class=> "btn btn-primary autotest"
Is it normal in Rails ?
Please gives me some advice, Thanks.
Upvotes: 0
Views: 639
Reputation: 24815
This is incorrect.
Problem 1: You have one whole big form for all the rows. When you submit, you want to delete the data on that row only, but you end with submit whole form. That's inefficient and error-prone. The fix is to build a form for each row(You can also use link_to and remote:true, which ends with each form per link as well)
Problem 2: Do not listen to the the form's submit and remove the row immediately. UJS(the processor of remote: true
) watches this event too. My guess is, though never done that before, the two listeners will have an order to execute as Javascript is single thread. If your listener was executed at first, the data got removed, then when UJS coming, it has no form fields to serialize and will cry :(
In problem 2, even if you don't remove the row, there is also another problem. What if the submit unsuccessful? Your listener marks the row as done no matter what the sever response is.
There are solutions inside jQuery Ajax such as using when
, done
. But since you are using UJS, the simplest solution is to render the scripts to execute at server response.
For example, your row 2 has a dedicated form. When submit, controller receives this request and then knows the task id. Then, in response js.erb, you can assign this specific div to be removed.
$('#task_#{task.id}').remove();
Upvotes: 1