2

I'm trying to validate a textarea making sure that each line starts with 'http://':

http://jsfiddle.net/n8zYB/1/

When the url is wrong, it executes the else statement but if it's correct, it isn't getting executed.

What's the problem?

Jürgen Paul
  • 14,299
  • 26
  • 93
  • 133

5 Answers5

2

It doesn't work because this refers to a String object. the after function expects a jQuery object or a string. Strangely enough, in javascript strings are different from String objects. Your else statement works because this is being converted into a string behind the scenes when you concat a regular string to it. However, the if fails because this remains a String object in this case. You can fix it in a couple of ways, but here is one of them:

$('button').click(function(){
    var links = $('textarea').val().split('\n');

    $.each(links,function(){
        if( this.substr(0, 7) == 'http://' )
            $('p').after(''+this);
        else
            $('p').after('error: '+this+'<br/>');
    });
    return false;
});

EDIT

here's a link to another SO question that discusses this in more detail Why are there two kinds of JavaScript strings?

Community
  • 1
  • 1
Brian Glaz
  • 15,468
  • 4
  • 37
  • 55
0

Don't use $.each to iterate an array. Use this:

for(var i = 0; i < links.length; i++) {
    if(links[i].substring(0, 7) !== 'http://' && links[i].substring(0, 8) !== 'https://') {
        $('p').text('Error!');
        return false;
    }
}

Here's a demo.

Ry-
  • 218,210
  • 55
  • 464
  • 476
0

It is not working because of $('p').after(this);. In this case, this is just a string literal.

The after function's first parameter should be an HTML string, DOM element, or jQuery object to insert after each element in the set of matched elements.

Here's an updated jsFiddle

chrisn
  • 2,095
  • 15
  • 20
0

How about this:

$('button').click(function(){
    var links = $('textarea').val().split('\n');

    $.each(links,function(){
        if( this.substr(0, 7) == 'http://' )
            $('p:last').after("<p>" + this + "</p>");
        else
            $('p:last').after('error: '+this+'<br/>');
    });
    return false;
});
Dessus
  • 2,147
  • 1
  • 14
  • 24
0

I think this would be little better, try it

$('button').click(function(){
    var links = $('textarea').val().split('\n');

    $.each(links,function(){
        if( this.substr(0, 7) == 'http://' )
            $('#mydiv').append(this + '<br/>');
        else
            $('#mydiv').append('<span style="color:red;">error: '+this+'</span><br/>');
    });
    return false;
});

HTML:

<textarea></textarea>
<button>Submit</button>
<div id='mydiv'></div>

fiddle : http://jsfiddle.net/n8zYB/6/

dku.rajkumar
  • 18,414
  • 7
  • 41
  • 58