当前位置: 动力学知识库 > 问答 > 编程问答 >

Character counter in jQuery for ajax loaded text area?

问题描述:

Character counting has been covered a lot - what I can't find out is how to get it to count dynamically loaded content.

I'm using jqEasy Character Counter which is a nice plugin for jQuery. It works beautifully with input/textareas on the same page but if I try and load in content via an ajax call it stops working. Here is my code so far :

This is the char counter:

$(document).ready(function(){

$(".countable").jqEasyCounter({

'maxChars': 250,

'maxCharsWarning': 230,

'msgFontSize': '11px',

'msgFontColor': '#000',

'msgFontFamily': 'Verdana',

'msgTextAlign': 'right',

'msgWarningColor': '#F00',

'msgAppendMethod': 'insertAfter'

});

});

This is the ajax call that loads the dynamic content :

 $(document).on("change", "#sitedrop_id", function(event){

$.post(

'load_site.php',

$("#siteselectform").serialize(),

function(data){

$("#sitedata").html(data)

}

);

return false;

});

This is one of the text areas of the form loaded in from another page :

<p>

<label for="headermsg_id" style="width:150px">Heading</label><textarea

class="countable" rows="4" cols="55" name="headermsg" id="headermsg_id"

style="resize: none; font-family:Arial, Helvetica, sans-serif; font-size:12px;">

</textarea>

</p>

I'm using jQuery 1.9.1 and I've tried $(document).on("change","#headermsg_id",function(event){ then the counter but thats not working either.

Any help would be greatly appreciated.

Thanks

网友答案:

Re-initialize the counter plugin after replacing your content with the ajax loaded stuff, e.g.:

var initCounter = function () {
    $(".countable").jqEasyCounter({
        'maxChars': 250,
        'maxCharsWarning': 230,
        'msgFontSize': '11px',
        'msgFontColor': '#000',
        'msgFontFamily': 'Verdana',
        'msgTextAlign': 'right',
        'msgWarningColor': '#F00',
        'msgAppendMethod': 'insertAfter'                
    });
};


$.post({
    ...
    function(data){
      $("#sitedata").html(data);
      initCounter();
    }
});
网友答案:

There is no element with ID sitedata in your posted code. Try replacing

$("#sitedata").html(data)

with

$("#headermsg_id").html(data)

because this is the only element you've posted which has the class countable and only those elements gets counted because you've initialized the easyCounter with the selector ".countable"

分享给朋友:
您可能感兴趣的文章:
随机阅读: