I have a comment form on a blog I’m building.
Blog posts are lengthy, so the form is located way off-screen, at the bottom of the page.
If a comment fails validation, then the user is taken back to the top of the page, but the error messages are displayed way down where the form is.
I’d prefer to have the browser focus on the comments section, when this happens, so that the user can see the validation error messages.
Here’s my comments_controller’s create action:
def create
@article = Article.find(params[:article_id])
@comment = @article.comments.build(params[:comment])
if @comment.save
redirect_to article_path(@article), notice: "Thanks for your comment"
else
# is there anyway to pass an id (like #comments) to this render call??
render 'articles/show'
end
end
As you can see, I call render 'articles/show' if validations fail. I was hoping to be able to do something like this though:
render 'articles/show', :anchor => '#comments'
In the ideal world, the code above would render articles#show, and set the viewport focus on the comments section. I know I can pass an anchor when using link_to, but can I do it with render?
Is anything like this possible, or do I need to go with an Ajax solution?
You don’t need Ajax – simple jquery should work.
Something like this (replacing ‘.error-messages’ with your error class):
On page load, if there are any error messages, the page scrolls to the error messages.