LalaByte
LalaByte

Reputation: 139

The if statement not working properly in Javascript

I am trying to create a logic that if anyone enters "<p>" and "</p>" characters inside <textarea>, then only Jquery should show the win message.I have a textarea with class html, a h2 with class result which shows win or loss.By now, I have this code:

var html = $('.html').val();
if(html.indexOf("</p>" && "<p>") === -1)
{
document.getElementById("result").innerHTML = "You lost it.";
}
else{
document.getElementById("result").innerHTML = "Hurray!You won";
}

But, this code is only checking if the <p> is there and not checking for </p>.So what can I do....

Upvotes: 2

Views: 109

Answers (3)

Barmar
Barmar

Reputation: 780909

The expression "</p>" && "<p>" is equivalent to "<p>" -- && evaluates each of its arguments from left to right, and returns the last truthy argument. Since both strings are truthy, what you wrote is effectively:

if (html.indexOf("<p>") === -1)

If you want to test whether a string contains two substrings, you have to call indexOf separately for each of them:

if (html.index("</p>") !== -1 && html.indexOf("<p>") !== -1)

Upvotes: 5

lordstyx
lordstyx

Reputation: 785

From MDN (Logical Operators) - Logical And (&&):

Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.

</p> isn't being evaluated as false, so the second value is returned which is <p>.

This means that you're only checking for the index of <p>. Try this instead:

var html = $('.html').val();
if (html.indexOf("</p>") === -1 && html.indexOf("<p>") === -1) {
    document.getElementById("result").innerHTML = "You lost it.";
}
else {
    document.getElementById("result").innerHTML = "Hurray! You won";
}

Upvotes: 2

Tom Fenech
Tom Fenech

Reputation: 74605

.indexOf takes a single string as an argument. You cannot combine string elements together using && like that.

The simplest way to modify your code would be to make two separate checks, one for the opening tag and one for the close:

if (html.indexOf("</p>") !== -1 && html.indexOf("<p>") !== -1)

This makes two separate checks for the two strings.

Alternatively, you could create a jQuery object from the HTML fragment inside your <textarea>, then check that it has no children that are <p> tags:

if ($('<div>'+html+'</div>').find('p').length > 0) {
    // the textarea contains some <p> tags
}

Upvotes: 1

Related Questions