在屏幕上显示时计算textarea字符(之前隐藏)

时间:2015-01-23 05:18:27

标签: jquery

我有这个HTML代码:

<div id="mylist" class="row">
    <form>
        <select class="form-control">
            <option selected="selected" value="0">Please select</option>
            <option value="1">Option 1</option>
            <option value="2">Option 2</option>
        </select>
    </form>
</div>


<div id="myform" class="row">
    <form>
        <div class="form-group">
            <label for="example"><span id="option-selected"></span></label>
            <textarea id="mymessage" class="form-control"></textarea>                       
            <div id="charNum"></div>
        </div>
      <button type="submit">Save</button>
    </form>
</div>

我有这个jQuery脚本:

<script>
function countChar() {
    var len = $('#mymessage').val().length;
    $('#charNum').text(len+' characters');
};

$(document).ready(function(){
    $("#myform").hide();
    $("#mylist select").on('change', function(){
        $("#myform").show();        
        if (selectedCampaignValue == 0){
            $("#myform").hide();
        }
    });

    countChar();
    $('#mymessage').change(countChar);
    $('#mymessage').keyup(countChar);
});
</script>

这是关于它的一些故事:

  • 默认情况下,#myform处于隐藏状态,仅在选择了#mylist上的某个值时才会显示。
  • textarea #mymessage字符与countChar()函数完全匹配。

然而,countChar()只在我在textarea上输入内容时开始计算。不是在选择时屏幕上显示#myform时。

如何countChar()立即计算textarea #mymessage字符(由#mylist选择触发)

谢谢。

2 个答案:

答案 0 :(得分:1)

当您展示countChar()时,您可以触发#myform

$("#mylist select").on('change', function(){
    $("#myform").show();        
    countChar();
    if (selectedCampaignValue == 0){
        $("#myform").hide();
    }
})

或者您可以触发#mymessage的{​​{1}}事件:

change

其中任何一个都可以完成您所寻求的目标,但我会建议第一个,因为它更简单,更快。

答案 1 :(得分:0)

您可能需要根据您的描述进行更改

if ($(this).val() == 0){
       $("#myform").hide();
}

而不是

if (selectedCampaignValue == 0){
     $("#myform").hide();
 }

<强> Demo