Friday 12 October 2012

HTML element: be careful of using element.value where there are newlines!

I'm working on a project where it uses a dirty check mechanism to warn the users on the page to save their data, and it uses element.value to retrieve the value for all form fields, and compare against the values at the time that the user navigates away from the page. This works great but unfortunately I found that element.value and $(element).val() does not always equal each other. You see, in OS specific systems, if there is a new line character, it will interpret it as \r\n, where as other OSes will interpret it as \n. By wrapping the element in jQuery, it will `normalize` the data for you so you don't have to worry about the subtle differences. For us it was essential that they have to be consistent, which is why one should use the jQuery implementation of .val() instead of element.value.

No comments:

Post a Comment