Ramirez
Ramirez

Reputation: 193

jQuery character count if statement

I have the following character count plugin:if there is more than 9 characters the alert class is added to change the color to red. What I want is when I say 'if number of character is more than 9', to replace the number 9 with a var.

if(number_of_characters >= 9) {

So this value can always be adjusted from the plugin options, instead of changing this value inside the jQuery plugin.

How should I do this?

My working fiddle

Upvotes: 0

Views: 71

Answers (3)

Sebri Zouhaier
Sebri Zouhaier

Reputation: 745

use the option Amount_Limit

$(textarea).CountCharacters({
    Start_Count: 0,
    Amount_Result: "counter",
    Alert_Class: "alert-counter",
    Amount_Limit: 9
});

if(number_of_characters >= options.Amount_Limit)

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337637

You can add a new property to the defaults object, and read from that. This can then be overridden as needed for each instance. Try this:

// declaration:
var defaults = {
    Start_Count: 0,
    Amount_Result: false,
    Alert_Class: false,
    maximumCharacters: 9
}

// usage:
 if (number_of_characters >= options.maximumCharacters) {
    $("#" + options.Amount_Result).addClass(options.Alert_Class);
} else {
    $("#" + options.Amount_Result).removeClass(options.Alert_Class);
}

Updated fiddle

Upvotes: 0

Alex Booker
Alex Booker

Reputation: 10777

Here is a working Fiddle.

What I did was add a new option - number_of_characters (you can name it w/e you want):

$(textarea).CountCharacters({
    Start_Count: 0,
    Amount_Result: "counter",
    Alert_Class: "alert-counter",
    Amount_Limit: 19,
    number_of_characters: 5
});

Then, instead of hardcoding the value, I referred to the new option:

if(number_of_characters >= options.number_of_characters) {
    $("#"+options.Amount_Result).addClass(options.Alert_Class);
}

I also set a new default option:

var defaults = {
  Start_Count: 0,
  Amount_Result: false,
  Alert_Class: false,
  number_of_characters: 9
}

Upvotes: 2

Related Questions