Reputation: 113
How can i check if text begin with ABCxx or ABCxxxx return true . tried using contains or attribue value but all return true
<input id="uxPromoCode" name="uxPromoCode" value="" class="form-input">
if("#uxPromoCode:contains('ABC')" ){ // $("#uxPromoCode[value^='ABC']")
Dialog.msg({
title: Message.dlg.title4,
msg: 'TRUE CODE',
});
}else{
Dialog.msg({
title: Message.dlg.title4,
msg: 'FALSE CODE',
});
}
Example:
ABCJ8 -true
ABCJ89K -true
ABCKL -true
KLHXN -false
C7HKLOJ -false
Upvotes: 0
Views: 38
Reputation: 28771
Below $("#uxPromoCode").val()
will give you value contain in textbox and indexOf()
function checks whether string ABC is present anywhere in textbox value.
if($("#uxPromoCode").val().indexOf("ABC") != -1 ){
Dialog.msg({
title: Message.dlg.title4,
msg: 'TRUE CODE',
});
}else{
Dialog.msg({
title: Message.dlg.title4,
msg: 'FALSE CODE',
});
}
To check for start of string is ABC use match regex function . The character ^ indicates check at start of string contained in textbox
if($("#uxPromoCode").val().match("^ABC")){
Dialog.msg({
title: Message.dlg.title4,
msg: 'TRUE CODE',
});
}else{
Dialog.msg({
title: Message.dlg.title4,
msg: 'FALSE CODE',
});
}
Upvotes: 2
Reputation: 29683
You can use .match
here with regex. The way you are currently implementing it is kind of CSS
attribute and it results in true
even if it finds AB
at beginning. Below is the snippet how you can use .match
$('.validate').on('click', function() {
if ($("#uxPromoCode").val().match('^ABC')){
/*Dialog.msg({
title: Message.dlg.title4,
msg: 'TRUE CODE',
});*/
console.log(true);
} else {
console.log(false);
/*Dialog.msg({
title: Message.dlg.title4,
msg: 'FALSE CODE',
});*/
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="uxPromoCode" name="uxPromoCode" value="" class="form-input"/>
<input type="button" value="Validate" class="validate"/>
Upvotes: 1
Reputation: 26278
Use JS Regular Expression like:
var haystack = 'hello world';
var needle = 'he';
if (haystack.indexOf(needle) == 0) {
// your code if string starts with 'he'
}
Upvotes: 0