0

I want to create a Character Counter for a Custom Field on a Product Page. I am trying to use the following JavaScript and HTML code to achieve such a function:

HTML:

<div class="fields-group-1">    

    <table class="fields_table  product-custom-text-wrapper" cellspacing="0">
        <tbody>
            <tr>
                <td class="label"><label class=" product-custom-text-label" for="custom_text">Custom Text</label></td>
                <td class="value">
                <input type="text" class="field product-custom-text" name="custom_text" value="" placeholder="Enter Custom Text ..." maxlength="16" type="text" pattern="mandatory" mandatory="no"  />
                    <span class="validation-message is-valid-1"></span>
                </td>
            </tr>
        </tbody>
    </table>


</div>

<span id="character_count"></span> //This is where I am attempting to output the Character Count.

JavaScript:

<script type="text/javascript"> 
$('.product-custom-text').keyup(updateCount);
$('.product-custom-text').keydown(updateCount);

function updateCount() {
    var cs = $(this).val().length;
    $('#character_count').text(cs);
}
</script>

When running this within the Fiddle program, I can generate the Character Counter. However, when I place the above code into the website, the Character Counter does not seem to work. I have checked the Source Code and all of the coding is there.

I can see that someone else has experienced a similar issue to myself, as per th question at: Code works in fiddle, but not on webpage. As a newbie to JavaScript, I am not 100% sure of a suitable fix.

Is anyone able to point me in the right direction as to the relevant changes I would need to make in order for my above coding to work?

Community
  • 1
  • 1
Craig
  • 1,872
  • 5
  • 23
  • 56
  • Can you please post a link to your fiddle. – Hector Barbossa May 08 '17 at 22:23
  • Are you importing jQuery to your page? Also try wrapping your first two lines inside `$(document).ready(function(){})` – Lixus May 08 '17 at 22:23
  • Wrap your JavaScript in `$(document).ready(function() { })` – DiddleDot May 08 '17 at 22:23
  • 1
    You are using jquery as well. JSFIddle has it innately. However when you are including your script inside your html you also have to add jquery to your scripts tags and wrap your code in `$(document).ready(function(){})` – Ozan May 08 '17 at 22:24

3 Answers3

1

You can change your binding like below:

jQuery(document).on('keyup', '.product-custom-text', updateCount);
jQuery(document).on('keydown', '.product-custom-text', updateCount);

This binding does not require to be inside $( document ).ready(function() { function, because it will work for available DOM elements

You need to use document.ready for keyup event. Before this moment DOM elements you're referring in jQuery selectors aren't available.

jQuery(document).on('keyup', '.product-custom-text', updateCount);
jQuery(document).on('keydown', '.product-custom-text', updateCount);

function updateCount() {
    var cs = $(this).val().length;
    jQuery('#character_count').text(cs);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fields-group-1">    

    <table class="fields_table  product-custom-text-wrapper" cellspacing="0">
        <tbody>
            <tr>
                <td class="label"><label class=" product-custom-text-label" for="custom_text">Custom Text</label></td>
                <td class="value">
                <input type="text" class="field product-custom-text" name="custom_text" value="" placeholder="Enter Custom Text ..." maxlength="16" type="text" pattern="mandatory" mandatory="no"  />
                    <span class="validation-message is-valid-1"></span>
                </td>
            </tr>
        </tbody>
    </table>


</div>

<span id="character_count"></span>

Edit: As per discussion, In wordpress sites, there might be chances of having $ confliction, so try using jQuery insted of $. Updated answer!

Mahesh Singh Chouhan
  • 2,558
  • 1
  • 16
  • 26
  • Thanks for your suggestion. I have tried this but to no success. Regarding ``, does it matter whether I enqueue this via the `functions.php` file or hard code it directly into the page's template page? – Craig May 08 '17 at 22:51
  • @Craig you have to include `` on your page, where you are using jquery code to make it work – Mahesh Singh Chouhan May 08 '17 at 22:53
  • Do not enqueue this via the functions.php, just copy and paste to include jquery script on that page – Mahesh Singh Chouhan May 08 '17 at 22:54
  • Unfortunately, I copied your suggested code as you placed here but to no success. – Craig May 08 '17 at 22:55
  • Ok, can you please check your browser console and put the javascript error here. – Mahesh Singh Chouhan May 08 '17 at 22:55
  • The only errors I have are: `JQMIGRATE: Migrate is installed, version 1.4.1 and Uncaught TypeError: $ is not a function at (index):1452 (anonymous) @ (index):1452` – Craig May 08 '17 at 22:57
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/143730/discussion-between-mahesh-singh-chouhan-and-craig). – Mahesh Singh Chouhan May 08 '17 at 22:57
  • Many apologies for contacting you again. The advised code conflicts with the Basket feature and prevents products from being shown. Any ideas on why this is? This is the code ` ` – Craig May 08 '17 at 23:35
  • Hey @Craig, please check the discussion chat – Mahesh Singh Chouhan May 08 '17 at 23:37
0

You are using jQuery functions, but are you importing jQuery to use it in your site? Also, your function should be wrapped in a jQuery docready function.

$( document ).ready(function() {
    //your code
});

It works in the Fiddle, because jsFiddle includes jQuery for you. In your build you have to import it.

Korgrue
  • 3,430
  • 1
  • 13
  • 20
0

As you pointed out it's wordpress: no need to include the jquery source. WP enqueues it by default (though other plugins can remove that)

Wrap your jquery code inside $.ready.

For wordpress: it forces no-conflict mode, and therefor for all jquery code you must use jQuery instead of the $ alias, OR use the following as the $.ready wrapper: jQuery(function($){ // your code with $ stuff });

yezzz
  • 2,990
  • 1
  • 10
  • 19