开发者

jquery return value of input to var

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 = {
    'm开发者_StackOverflow社区axCharacterSize': 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


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);
});


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())
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜