timmack
timmack

Reputation: 590

How to check an entire string if it contains a specific word using jQuery?

I need help on checking a certain word if it contains in a string that is being assigned into my input textbox. For example below, If there's a string value assigned to this textbox

<input type="text" id="StartLocation" name="StartLocation" value="1 AAC, MT SECTION, RAF SCAMPTON, LINCOLN, LN1 2ST, UNITED KINGDOM" >

I want to check if it contains the word "UNITED KINGDOM" and if does not, it should return false. I tried something like this below but it keeps returning true because the alert message is always 'It contains United Kingdom' even though I already change the value.

if ($("input#StartLocation:contains('UNITED KINGDOM')")) {
  alert('It contains United Kingdom');
} else {
  alert('It does not contains United Kingdom');
}

How do I fix this? Thanks...

Upvotes: 0

Views: 3505

Answers (5)

I prefer this approach, because it's more readable. But please check browser compatibility first.

if ($("#StartLocation").val().includes('UNITED KINGDOM')) {
  //your code
}

Upvotes: 1

4b0
4b0

Reputation: 22323

Try this way. Use indexOf.

var value = $("#StartLocation").val();
if(value.indexOf("UNITED KINGDOM") != -1)
  alert("true");
else
  alert("false");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="StartLocation" name="StartLocation" value="1 AAC, MT SECTION, RAF SCAMPTON, LINCOLN, LN1 2ST, UNITED KINGDOM">

Upvotes: 1

Thu San
Thu San

Reputation: 1544

try this

if ($("#StartLocation").val().indexOf('UNITED KINGDOM') >= 0) {

}

Upvotes: 1

Barmar
Barmar

Reputation: 780724

You don't use :contains to test the value of an <input> element, it's for containers like <div> and <span>. Use .val() to get the value, and then use ordinary string methods.

if ($("input#StartLocation").val().indexOf("UNITED KINGDOM") != -1)

Upvotes: 2

Suresh Atta
Suresh Atta

Reputation: 121998

You can try val() and indexOf

if ($("input#StartLocation").val().indexOf('UNITED KINGDOM')>-1)) {
   //.. ToDO
}

Upvotes: 0

Related Questions