简体   繁体   中英

New to Ajax…how can I return my CSS to it's default value after an ajax call? (e.g. reload CSS)

Alright so I'm using a jQuery ajax() call to get a response from a php page in order to submit/check a form. When it's successful, it gets returned a list of form elements and corresponding messages saying whats wrong with them (eg missing field, invalid input, etc).

It then uses jQuery again to loop through each of the form elements returned by the ajax call and alters their css (imported via ) - eg makes the elements border red, to indicate an error with that element.

This works pretty well. But, let's say I submit the form with a missing field - ajax makes the call, and the page's css gets altered to highlight that field with red. Now let's say I fix the problem with that field (eg give it valid data) and resubmit, but this time with a different field missing. While it will properly give the new missing field a red border, it won't take away the red border from the field that was correctly on resubmission. In other words, I can never clear the red border once it's there.

I'm thinking I might need to do a "reload css"-type function in javascript to reload the css after the ajax call...or something? I don't really know. This seems like it should be a really common thing to want to do, though. Reading around, it looked like it may have something to do with caching the page, but I don't think I have control over that sort of thing.

Might be worth mentioning I'm using Less CSS. Halpz?

Not sure how the borders/styles are being added in the callback, But I'd suggest adding a css class to the form fields that are missing with the styles declared in that class. Then using an 'if' statement or :focus event, remove class when users click back into it.

I think you are over-thinking this. You don't want to modify the CSS directly with jQuery. You just want to toggle classes on and off.

So if this is your field:

<input type="text" />

And there's an error, have the server return this:

<input type="text" class="error" />

Then if you need to toggle the error state off

$theInput.removeClass("error")

That way you're not touching CSS directly at all and there's no need to 'reload' it (not that that would fix the problem).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM