Search code examples
javascriptjqueryreplacegreasemonkeyblur

Character submitted wrong after replace


i use a greasemonkey script to replace any commas or semicolons from fields. There are several internal websites where i have to do this, some only with input fields, some with textarea.

The script actually works, but when i submit the form, the replaced characters of the textareas will still get submitted as commas and semicolons.

To be sure that the submit will not be triggered before last blur, i added a alert.

(function() {
'use strict';

$(document).ready(function(){
$("textarea").blur(function(){
    this.value=this.value.replace(/[,;]/g, "-");
    this.value=this.value.replace(/\n/g, " ");
});
$("input").blur(function(){
   this.value=this.value.replace(/[,;]/g, "-");
   this.value=this.value.replace(/\n/g, " ");
});
});

var nodes = document.getElementsByTagName('input');
if (window.location.href == "<website-url>")
nodes[39].setAttribute('onclick', 'alert("Data validated")');
    else
nodes[0].setAttribute('onclick', 'alert("Data validated")');

Any ideas? Tested with different browsers and different characters.


Solution

  • I'd use the submit event to make sure any lingering changes not handled yet by blur are handled before submission:

    $(document).ready(function() {
        function updateValue() {
            this.value = this.value.replace(/[,;]/g, "-").replace(/\n/g, " ");
        }
        $("textarea, input").blur(updateValue);
        $("form").submit(function() {
            $(this).find("textarea, input").each(updateValue);
        });
    });
    

    Sadly, Stack Snippets don't allow forms, so here's the above live on jsFiddle. Note that if you type, say, cute;kittens into the field and then either tab out of it or submit it, it's changed to cute-kittens and that's the value that gets submitted to Google if you send the form.