2

Well, I have a Javascript function that returns the number of words that I write into a textarea, but for some reasons, I wanted to write it using Jquery. And, although I tried, I didn't managed to get it, so that's why I'm here, I would be very, very grateful if you could help me.

This is the Javascript:

function contar() {
palabras = 1;
if (document.data.texto.value.length === '') palabras = 0;
for (count = 0; count < document.data.texto.value.length; count++) {
    if (document.data.texto.value.substring(count, count + 1) == ' ') palabras++;
}
document.data.cuenta.value = palabras;}

And this is the jQuery I've made:

(function () {
    var palabras = 1;
    if ($("[name=data] textarea[name=texto]").val().length === "") {
        palabras = 0;
    }
    for (i = 0; i < $("[name=data] textarea[name=texto]").val().length; i++) {
        if ($("[name=data] textarea[name=texto]").val().substring(i, i + 1) == ' ')) {
            palabras++;
        }
    }
});

Finally, this is the HTML I use to display it:

<form name="data">
    <textarea name="texto" cols="40" rows="4" onkeyup="contar()" onkeypress="contar()"></textarea>
    <br>
    <input type="Text" name="cuenta" size="3" maxlength="3">
</form>
Saram
  • 1,500
  • 1
  • 18
  • 35
user3019527
  • 33
  • 1
  • 3
  • `.length` is an interger, not a string, so `.length === ""` will not work. – putvande Nov 21 '13 at 22:10
  • That doesn't really count the words now, does it ? – adeneo Nov 21 '13 at 22:11
  • has it count spaces only or need to omit multispaces? – Saram Nov 21 '13 at 22:12
  • About this line : `if (document.data.texto.value.length === '')` How a length could be equals to an empty string ? And you should access you nodes with `document.getElementById` function, way more practical; – OlivierH Nov 21 '13 at 22:16
  • [Duplicate] mark is pointless. Major problem was to count **words** not **characters**. This problem has no solution in suggested duplicate question. – Saram Nov 22 '13 at 11:48

3 Answers3

4

A working solution :

function contar(){
        alert($.trim($('[name="texto"]').val()).split(' ').filter(function(v){return v!==''}).length);
}

The filter(function(v){return v!==''}) part removes empty strings.

http://jsfiddle.net/qhaYH/

OlivierH
  • 3,875
  • 1
  • 19
  • 32
  • I've managed to make it work (I needed a window load event and to change all the "$" as the host converted them to $, but that's all). Moreover, I've removed the .on event as the .click is the only event used, so I thought it wouldn't be necessary. Anyway, you've saved my life, thanks for that :P – user3019527 Nov 22 '13 at 13:46
1

The simplest solution that cross my mind follows:

//function
function countWords(tx){
  return tx?tx.replace(/ +/g," ").replace(/\w+| $|^ /g,"").length+1:0;
}
//jQuery plugin
$.fn.countWords = function(){
 return countWords(this.val()) ;
};

Example HTML:

<textarea id="tester"></textarea>
<p>WordsCount:<span id="counter">0</span></p>

JS:

$tester = $("#tester");
$tester.keyup(function(e){
  $("#counter").text($tester.countWords());
});

http://jsbin.com/EfukoYIs/3/edit?html,js,output

Edit
Finally I changed concept to count only words in proper meaning (no special chars etc.). The code follows:

//function
function countWords(tx){
  return tx.replace(/\w+/g,"x").replace(/[^x]+/g,"").length;
}

IMO it's much better. http://jsbin.com/EfukoYIs/5/edit?html,js,output

Saram
  • 1,500
  • 1
  • 18
  • 35
  • Yes, it works in the jsbin, but when I try to use it in the web page, I can't manage to use it properly (maybe it's host's fault, because I don't really know what version of jQuery they have, but I'm completely sure that they don't even have 1.9.1 :/) If you want to know, I've added the Jquery part between two script tags after the srcipt of the jquery, but it don't even works in jsbin >.< Yes, I know I'm very noob at this... – user3019527 Nov 22 '13 at 13:15
  • Maybe visibility scope is your problem. It's hard to say from my position. I assumed that major problem is to convert you function logic to be used in jQuery manner. For your HTML code just simple code should work: `alert($('[name="texto"]').countWords());` – Saram Nov 22 '13 at 17:31
-2

Get the value of the textarea, and split it on the space character which will give you an array. Then return the length of that array.

Updated for empty string http://jsfiddle.net/ghyDs/1/

<script type="text/javascript">
    function contar() {
        var value = $.trim($('[name="texto"]').val()),
            count = value == '' ? 0 : value.split(' ').length;

        $('[name="cuenta"]').val(count);
    }
</script>
NaNpx
  • 530
  • 3
  • 7