How to take a json object and output a UL/LI on the page
using rails, if there are errors, I get back something like so:
{"email":["has already been taken"]}
How can I take that JSON and create a UL on the page of the errors
<div id="errors">
<ul>
<li><b>Email</b> has already been taken</li>
<ul>
</div>
Update
If I alert the error object provided by rails I get:
开发者_开发百科{"email":["can't be blank"]}
Thanks
I don't understand why you have an array as the value of "email", the data format looks odd to me. BUT using your JSON verbatim, here's what you can do (I assume you'll have multiple error values):
var myJSON = {"email":["has already been taken"], "password":["has already been taken"]};
var html = '<ul>';
for (var key in myJSON)
{
html += '<li><b>' + key + '</b> ' + myJSON[key][0] + '</li>'
}
html += '</ul>';
document.getElementById('errors').innerHTML = html;
To capitalize "Email", you just need to define CSS style like so:
#errors li b
{
text-transform:capitalize;
}
PS: This could be much cleaner/easier if you use a JS framework.
It seems to me what you have should work. You have it all, you just did not show your .js partials which I'm sure you have:
def update
respond_to do |format|
if @user.save
format.js
else
@errors = @user.errors
format.js { render 'errors.js'}
end
end
end
I'm assuming you are using jQuery.
app/viiews/users/update.js
This one you just need a flash notice or something.
app/viiews/users/errors.js
jQuery("#errors").html("<div><%= escape_javascript(render(@errors)) %></div>");
make sure you repalce jQuery with $ if that is what you are using.
You need to have this in your devise edit area app/views/devies/registrations/edit:
<ul id="errors">
<%= render @errors if @errors %>
</ul>
Then you can redefine you errors partial:
app/views/users/_errors.js
<li>
<%= error.name %> or whatever value.
</li>
jQuery's $.map
could be used for this (I noticed the question was tagged jquery):
var messages, errorMarkup = '';
for (var error in errors) {
messages = errors[error];
errorMarkup += "<ul>" + $.map(messages, function(el) {
return "<li><b>" + error +"</b> " + el + "</li>";
}).join('') + "</ul>";
}
$("#errors").append(errorMarkup);
(If you really wanted to get crazy you could reduce this even further)
Here's an example: http://jsfiddle.net/ymPsu/
Edit: Here's the crazy version, using only
$.map
:
var errorMarkup = $.map(errors, function(errorList, key) {
return "<ul>" + $.map(errorList, function(message) {
return "<li><b>" + key + "</b> " + message + "</li>";
}).join('') + "</ul>";
}).join('');
$("#errors").append(errorMarkup);
精彩评论