开发者

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 cou开发者_运维知识库ld 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.


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/


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(";"))
    });
});


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜