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...
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)
try this
if ($("#StartLocation").val().indexOf('UNITED KINGDOM') >= 0) {
}
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">
I prefer this approach, because it's more readable. But please check browser compatibility first.
if ($("#StartLocation").val().includes('UNITED KINGDOM')) {
//your code
}
You can try val()
and indexOf
if ($("input#StartLocation").val().indexOf('UNITED KINGDOM')>-1)) {
//.. ToDO
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.