Question

I'm wanting to implement a real-time word counter in a form. So as a user types into the box, a line below the box updates with the correct number of words.

Here is the relevant form code (my views are .html.haml):

= f.semantic_fields_for :student_biography do |fb|
  = fb.inputs :name => "About" do
    = fb.input :short_statement, :label => 'Describe yourself! (25 words) ' , :input_html => {:id => "bio_prof_stmt" }

So below this description box, I'd like to count the number of words and display an 'out of 25' notice.

I'm assuming that this is just some javascript I need to add, but I don't know where to proceed from here.

Rails 3.2.11, Ruby 1.9.7

Thanks!

Was it helpful?

Solution

It shouldn't be too difficult, you would need a div that had its content updated on the keyup event for the input box:

This is a little bit from memory and may need some adjustment but it should get you on the right path:

= fb.input :short_statement, :label => 'Describe yourself! (25 words) ' , :input_html => {:id => "bio_prof_stmt" }, :onkeyup => "update_word_count(this);"

I think this is the right haml syntax, please correct me if not:

#word-count-container 

The intended html:

<div id="word-count-container"></div>

Javascript:

<script type="text/javascript">
  function update_word_count(object) {
    words = object.value.match(/\S+/g).length.toString();
    $('#word-count-container').innerHTML = words + " out of 25 used";
  }
</script>

Alternative UJS approach (remove the onkeyup tag from the input):

<script type="text/javascript">
  $('#short_statement').onkeyup(function() { 
      update_word_count(this);
  });

  function update_word_count(object) {
    words = object.value.match(/\S+/g).length.toString();
    $('#word-count-container').innerHTML = words + " out of 25 used";
  }
</script>

OTHER TIPS

This seems like something that you have to validate on the server side as well as the client side. So don't forget to do that.

validates :short_statement, length: { maximum: 25 }

If you want strict word counting you can use the Words Counted gem. Disclaimer I wrote it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top