0

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...

guradio
  • 15,524
  • 4
  • 36
  • 57
timmack
  • 590
  • 2
  • 12
  • 43
  • `:contains` is for matching the text of container elements like `DIV` and `SPAN`, it doesn't match the value of inputs. – Barmar Feb 08 '18 at 03:20
  • `contains` doesn't check attributes ... perhaps you want to check `[value*='UNITED KINGDOM']` - e.g. https://jsfiddle.net/xmkj07jh/ – Jaromanda X Feb 08 '18 at 03:21
  • Possible duplicate of [JQuery string contains check](https://stackoverflow.com/questions/3728022/jquery-string-contains-check) – Touheed Khan Feb 08 '18 at 03:23

5 Answers5

2

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)
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

try this

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

}
Thu San
  • 1,400
  • 1
  • 17
  • 29
1

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">
4b0
  • 21,981
  • 30
  • 95
  • 142
1

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

if ($("#StartLocation").val().includes('UNITED KINGDOM')) {
  //your code
}
Iván E. Sánchez
  • 1,183
  • 15
  • 28
0

You can try val() and indexOf

if ($("input#StartLocation").val().indexOf('UNITED KINGDOM')>-1)) {
   //.. ToDO
}
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307