0

I have this simple page: http://jsfiddle.net/20140228/2cjw9h9n/1/

It uses this WordCount code as a starting point: http://jsfiddle.net/deepumohanp/jZeKu/

But is much more basic, containing only the Word Count part of the code.

I need to pass the value of the wordCount Javascript variable to the "varCount" hidden form field variable.

I have looked at this page: Pass a javascript variable value into input type hidden value

But I can't work out how to implement the suggestions from the page into my page, as my Javascript understanding is rather basic!

I suppose it would have to include something like:

document.getElementById('varCount').value = ???;

How would I achieve this?

Community
  • 1
  • 1

4 Answers4

2

If you are using jquery

$('#varCount').val('your-value');

val can do a read or write operation on a particular DOM element simultaneously

val() - when called without a parameter reads the value of DOM element

val('value') - when called with a parameter writes the value to a DOM element

Prabhu Murthy
  • 9,031
  • 5
  • 29
  • 36
1

I've a little bit modified your code.

<script>
setWordCount = function(wordCount){ 
    $('#wordCount').html(wordCount);

    // jQuery solution (this is what you actually need)
    $('#varCount').val(wordCount);

    // Commented below is plain JS solution (just in case you're curious)
    // document.getElementById('varCount').value = wordCount;
};

counter = function() {
    var value = $('#text').val();

    if (value.length == 0) {
        setWordCount(0);
    } else {
       var wordCount = value.trim().replace(/\s+/gi, ' ').split(' ').length;
       setWordCount(wordCount);
    }
};

jQuery(function($) {
    $('#count').click(counter);
    // No need to have keypress, keydown, the keyup event will handle it anyway.
    $('#text').change(counter).keyup(counter).blur(counter).focus(counter);
});
</script>
Htmlin.com
  • 121
  • 3
0

to pass value of your wordCount variable to your hidden field you can use this way:

$('#varCount').val(wordCount);

You need to write this into your counter function. DEMO

(In demo i have changed hidden field to text field, just to show changes.)

Rupali
  • 1,068
  • 1
  • 12
  • 18
0

Try this:

<script>
var abc;
abc = document.getElementById('wordCount').value;
<script>

The variable abc would get the value of the total number of words you have entered in the textarea.

halfer
  • 19,824
  • 17
  • 99
  • 186
Amrinder Singh
  • 5,300
  • 12
  • 46
  • 88