I am building an Rails 4.1 webapp and I am using a an ajax form (remote true) and a create.js.erb file with this content:
$("div.box-content").prepend('<%=j render @comment %>');
$(".empty-message").hide();
$(".textfield").val("");
How can I check if @comment is empty? Right now it´s adding an empty row when there is no content (I don't want to add a row if comment is not set).
Update
def create
@comment = @object.comments.create(comments_params)
end
You can either check server-side (conditionally output different JavaScript) or you can check in client-side in JavaScript.
Checking server-side involves testing whether @comment
is set, and simply not output any of the prepending JavaScript:
<% if @comment.present? %>
$("div.box-content").prepend('<%=j render @comment %>');
<% end %>
$(".empty-message").hide();
$(".textfield").val("");
Checking client-side involves outputting the empty value in a variable so you can inspect it in JavaScript vefore prepending it to your element:
var comment = '<%= j render @comment %>';
if (comment) {
$("div.box-content").prepend(comment);
}
$(".empty-message").hide();
$(".textfield").val("");
I would use the first approach.