views:

43

answers:

2

My buddy at work told me that you could use jQuery to write a few lines of code that would find a single character (in this example '\0') and replace it for all textboxes and textareas on the page. Of course, he didn't tell what lines of code would do that ...

Is there a simple way to do this? We have a problem of people copying data from an old system and the data having a '\0' at the end of the text. This then gets saved in the database, and then when brought back from the database to the client, it causes an error.

EDIT: I agree with Magnar's answer, but just for learning sake, does anyone know of a way to do this?

+5  A: 

This isn't a job for jQuery. I would strongly recommend you remove the null-character on the server side, for added stability and security reasons.

However, this is how you would do it (slightly verbose):

var remove_null_character = function () {
    var field = $(this),
        old_value = field.val(),
        new_value = old_value.replace('\0', '');
    field.val(new_value);
};
$("input:text, textarea").live("blur", remove_null_character);
Magnar
I totally agree with this btw, +1
Peter Kruithof
Thanks! That is easy, but I agree, I will keep this logic on the server.
Martin
+1  A: 

Javascript has string search/replace functions you can use. jQuery can fetch the specific input nodes for you, but the search/replace is just plain javascript:

str = str.replace('\0', '');

The replace function also works with regular expressions by the way, in case you need something more powerful.

Peter Kruithof