john mossel
john mossel

Reputation: 2156

Finding commas in strings using JS

I'm trying to learn JS, so forgive me if you code makes the world explode. Anyway, I am trying to make a tagging system interface similar to SOs. Where the user types in words and SO separates them on the comma (or on spacebar but I don't want that).

I am using jQuery to access the DOM (because it is so much easier), and I know there are various plugins that could do this and feed the homeless, but as I said I want to learn.

Here's what I have so far:

<input type="textbox" name="somebox" id"someid">

$(document).ready(function() {
    var startPos = 0;

    $("#someid").keyup(function() {
        var inputText = $(this).val();
        var commaPosition = inputText.indexOf(",", startPos);
        var foundWords = [];

        alert('Hello'); // even this doesn't work... why???
        if (commaSearch !== '-1') {

            // take the word:
            foundWords.push(inputText.slice(startPos,commaPosition));

            startPos = commaPosition + 1;
        }
    });
});

It can also be found here. Nothing seems to work, not even the alert. Any help would be grateful.

Upvotes: 0

Views: 94

Answers (4)

mplungjan
mplungjan

Reputation: 178011

Is this what you want?

DEMO

$(document).ready(function() {
    $("#someid").keyup(function() {
        var inputText = $(this).val();
        var foundWords = inputText.split(","); // or as posted elsewhere split(/\s*,\s*/g)
        if (foundWords.length>1) $("#tags").html(foundWords.join(";"))
    });
});

Upvotes: 0

Ry-
Ry-

Reputation: 224942

Is this what you want?

As Matt Ball pointed out, you're missing the = sign after id in your HTML. Next, you use commaPosition then commaSearch. Next, you use the not-identity operator with a number and a string, which will always return false.

Upvotes: 0

Phil
Phil

Reputation: 11175

You're going to laugh, but you didn't have the = infront of the id=someid :D http://jsfiddle.net/SuperPhil/9KVs4/2/

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 359836

Problems:

  • Invalid HTML - you're missing an = in between id and "someid". This will make the alert() work.
  • Use String.split(',') rather than String.indexOf(','). To split and get rid of extra spaces: inputText.split(/\s*,\s*/g)
  • I also get Uncaught ReferenceError: commaSearch is not defined. – Felix Kling

Demo with fixes: http://jsfiddle.net/mattball/2sE8b/

Upvotes: 2

Related Questions