I wanted to compare value with comma separated value in javascript or jquery. for that i did following code, what is remaining?:
var str = $('#reg').val();
// i got str = 1,2,3
i need to compare it with values so how can i do this:
if (str == 1) {
$('.WBE').show();
} else {
$('.WBE').hide();
}
if (str == 2) {
$('.VOBE').show();
} else {
$('.VOBE').hide();
}
if (str == 3) {
$('.MBE').show();
} else {
$('.MBE').hide();
}
If you are trying to check if the string contains 1,2, or 3 then you can do like this:
var str = $('#reg').val();
if(str.indexOf("1") != -1) {
$('.WBE').show();
} else {
$('.WBE').hide();
}
if(str.indexOf("2") != -1) {
$('.VOBE').show();
} else {
$('.VOBE').hide();
}
if(str.indexOf("3") != -1) {
$('.MBE').show();
} else {
$('.MBE').hide();
}
Or using ternary operator
$('.WBE')[~str.indexOf('1') ? 'show' : 'hide']();
$('.VOBE')[~str.indexOf('2') ? 'show' : 'hide']();
$('.MBE')[~str.indexOf('3') ? 'show' : 'hide']();
Looping through array and ternary operator
['WBE', 'VOBE', 'MBE'].forEach(function(class, index) {
$(class)[~str.index(index+1) ? 'show' : 'hide']();
});
This will only work if you have 0-9. If you have 2 or more digit numbers then you should probably convert to array and check if array contains the number...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With