0

Wanted to have a word counter next to a input textbox on the website

Got it working to show the count when the user click or modify the text but I wanted to load up straight away when the page finish loading.

$(document).ready(function() {

  $("#product_name").change(displayText).keyup(displayText);

function displayText(){
      $("em#counter").text($(this).val().length +' chars'); 
}
});

So I tried this the code below but couldn't get it working and don't know why.

$(document).ready(function() {

    if($("#product_name").length){
           displayText();
    }
  $("#product_name").change(displayText).keyup(displayText);

function displayText(){
      $("em#counter").text($(this).val().length +' chars'); 
}
});

Thanks so much.

1
  • We'll need more information to answer your question. Is it throwing an error? Commented Mar 1, 2013 at 6:30

2 Answers 2

2

Try this

if($("#product_name").length){
           displayText();
}
$("#product_name").change(displayText).keyup(displayText);

function displayText(){
      $("em#counter").text($("#product_name").val().length +' chars'); 
}

Demo: Fiddle

Problem was your displayText() call during page load. In displayText you had used $(this) to access the input field, which was working as a event handler. But when you call displayText directly this will point to the window object.

Sign up to request clarification or add additional context in comments.

Comments

0

Try .on() with multiple event.

$("#product_name").on({
    change: function() {
        // Handle change event
    },
    keyup: function() {
        // Handle keyup
    }
});

and for "when the page finish loading." use $(window).load(function() { });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.