henryaaron
henryaaron

Reputation: 6202

Script works at jsFiddle but not in Greasemonkey

I have this Greasemonkey script that works fine in the Fiddle. It's designed to capitalize the text entered in an input field. Unfortunately, when I try to implement it into Greasemonkey, it refuses to work.

Can anybody help me? I'm new at Greasemonkey.

The script (It's also at this jsFiddle):

// ==UserScript==
// @name           2
// @include        *
// @require        http://code.jquery.com/jquery-1.7.1.min.js
// ==/UserScript==
$(document).ready(function(){
$.fn.capitalize = function () {
    $.each(this, function () {
        var split = this.value.split(' ');
        for (var i = 0, len = split.length; i < len; i++) {
            split[i] = split[i].charAt(0).toUpperCase() + split[i].slice(1).toLowerCase();
        }
        this.value = split.join(' ');
    });
    return this;
};

$('input').on('keyup', function () {
    $(this).capitalize();
}).capitalize();
});

Upvotes: 0

Views: 356

Answers (2)

Brock Adams
Brock Adams

Reputation: 93623

Several things:

  1. The problem is probably an install conflict. The script from that jsFiddle does nominally work as a GM script.

    1. From the "Manage User Scripts" panel, uninstall the current script and any others with the same name.
    2. Restarting Firefox would also be a good idea.
    3. Save the code, below, to Capitalize_Inputs.user.js and then install it as a Greasemonkey script. (Adjust the include, exclude, and match directives.)

  2. You do not need to use $(document).ready() here or in most GM scripts.

  3. Avoid using @include * if you can. It speed things up and reduces potential conflicts.

  4. That capitalize() function could be better. At a minimum, replace:
    var split = this.value.split(' ');
    with:
    var split = this.value.split(/\s/); // Or split(/\s+/) depending on if multiple spaces desired


The resulting script would be like:

// ==UserScript==
// @name     _Capitalize inputs
// @include  http://YOUR_SITE/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
// ==/UserScript==

$.fn.capitalize = function () {
    $.each(this, function () {
        var split = this.value.split (/\s+/);
        for (var i = 0, len = split.length; i < len; i++) {
            split[i] = split[i].charAt(0).toUpperCase() + split[i].slice(1).toLowerCase();
        }
        this.value = split.join (' ');
    } );
    return this;
};

$('input').on ('keyup', function () {
    $(this).capitalize ();
} ).capitalize();

Upvotes: 1

Matthew Flaschen
Matthew Flaschen

Reputation: 285057

Works for me. Firefox 10.0.2, Greasemonkey 0.9.18. I'm using this fiddle, which is just an input (no library), to test.

Try to uninstall then reinstall the script.

Upvotes: 0

Related Questions