Question

I'm trying to make a variable equal the value of the text box. I have the text box value being set to a variable and returned as an alert (for now) but I can't figure out how to call that variable from other functions.

$('#max_char').keyup(function () {
    var max_char = $(this).val();
    alert(max_char + ' Handler for .keyup() called.');
});

var count_options = {
    'maxCharacterSize': max_char,
    'originalStyle': 'originalDisplayInfo',
    'warningStyle': 'warningDisplayInfo',
    'warningNumber': 40,
    'displayFormat': '#input Characters | #left Characters Left | #words Words'
};

$('#textinput').textareaCount(count_options);
});

HTML

<textarea cols="68" rows="21" name="textinput" id="textinput"></textarea><br/>
    <input type="textbox" id="max_char" name="max_char" value="-1" /> Max Characters <br/>

Any help would be great. Trying to add the var max_char to the maxCharacterSize of count_options

Was it helpful?

Solution

All you need to do is declare max_char in a higher scope, i.e. outside of the keyup function:

var max_char;

$('#max_char').keyup(function () {
    max_char = +$(this).val();
    alert(max_char + ' Handler for .keyup() called.');
});

Also note that I put a + in front of $(this).val() to convert it from a string into a number, since "1" + 1 == "11".


Update:

The reason the textareaCount plugin isn't working is because it is initialised once, on document ready. At this time, max_char is nothing because the user hasn't typed anything yet.

You'd have to either reconfigure or re-initialise the plugin on every keyup to get the effect you're after. Unfortunately the plugin doesn't document an easy way to do this. After digging through the plugin's source code, I think there are only 3 events it binds that you need to revert, before you can simply re-initialize it again. Try this out:

var count_options = {
    'maxCharacterSize': 100, // Just some default value
    'originalStyle': 'originalDisplayInfo',
    'warningStyle': 'warningDisplayInfo',
    'warningNumber': 40,
    'displayFormat': '#input Characters | #left Characters Left | #words Words'
};

// Initialise the plugin on document ready
$('#textinput').textareaCount(count_options);

$('#max_char').keyup(function () {
    var max_char = +$(this).val();
    count_options.maxCharacterSize = max_char;

    // Unbind the 3 events the plugin uses before initialising it
    $('#textinput')
        .next('.charleft').remove().end()
        .unbind('keyup').unbind('mouseover').unbind('paste')
        .textareaCount(count_options);
});

OTHER TIPS

If I understand you correctly, if you declare the var within the global scope of javascript

Or if you directly access the input with

$("#max_char").val()
parseInt($('#max_char').val())
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top