-1

I've set up my form with the code from this thread: Counting and limiting words in a textarea

However the fiddle code was written with jQuery 1.8.3 and it is working fine with that however, my wordpress site is using jquery 1.11.0 - what sort of modification do I need to make to the code for it to work with this version of jquery? Code below...

Thanks for your help.

<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>
<script type='text/javascript'>//<![CDATA[ 
$(function(){
$(document).ready(function() {
    $("#word_count").on('keydown', function(e) {
        var words = $.trim(this.value).length ? this.value.match(/\S+/g).length : 0;
        if (words <= 200) {
            $('#display_count').text(words);
            $('#word_left').text(200-words)
        }else{
            if (e.which !== 8) e.preventDefault();
        }
    });
 }); 
});//]]>  
</script>

  <textarea name="txtScript" id="word_count" cols="30" rows="10"></textarea>
Total word Count : <span id="display_count">0</span> words. Words left : <span id="word_left">200</span>
Community
  • 1
  • 1
user3809226
  • 83
  • 1
  • 4

1 Answers1

0

OK, it's not the jQuery versions that are having an impact as if I change the fiddle you referenced in this Counting and limiting words in a textarea answer found here http://jsfiddle.net/7DT5z/9/ to use jQuery 1.11.0 as seen here http://jsfiddle.net/robschmuecker/7DT5z/21/ it still works.

I believe it is the way jQuery is included by default in wordpress, you're referencing jQuery in normal mode but it includes itself in noConflict mode in wordpress by default which means $ (alias if jQuery) is not available and you need to user jQuery instead.

So your code would need to read:

jQuery(function(){
jQuery(document).ready(function() {
    jQuery("#word_count").on('keydown', function(e) {
        var words = jQuery.trim(this.value).length ? this.value.match(/\S+/g).length : 0;
        if (words <= 200) {
            jQuery('#display_count').text(words);
            jQuery('#word_left').text(200-words)
        }else{
            if (e.which !== 8) e.preventDefault();
        }
    });
 }); 
});

Another easier way of modifying code which references the short-form alias $ is this. - as beautifully explained and demonstrated here http://digwp.com/2011/09/using-instead-of-jquery-in-wordpress/

jQuery(document).ready(function( $ ) {
$("#word_count").on('keydown', function(e) {
        var words = $.trim(this.value).length ? this.value.match(/\S+/g).length : 0;
        if (words <= 200) {
            $('#display_count').text(words);
            $('#word_left').text(200-words)
        }else{
            if (e.which !== 8) e.preventDefault();
        }
    });
    });
Community
  • 1
  • 1
Rob Schmuecker
  • 8,934
  • 2
  • 18
  • 34