How to compare a comma separated value in javascript or jquery
I wanted to compare a comma separated value in javascript or jquery. why i did the following code, what's left ?:
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();
}
+3
source to share
2 answers
If you are trying to check if a string contains 1,2 or 3, you can do the following:
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 the ternary operator
$('.WBE')[~str.indexOf('1') ? 'show' : 'hide']();
$('.VOBE')[~str.indexOf('2') ? 'show' : 'hide']();
$('.MBE')[~str.indexOf('3') ? 'show' : 'hide']();
Quoting 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 digits of digits, you should probably convert to an array and check if the array contains a number ...
+1
source to share
You can convert a string value to an array and check the values ββit contains using $.inArray
:
var values = $('#reg').val().split(',');
$('.WBE')[$.inArray('1', values) != -1 ? 'show' : 'hide']();
$('.VOBE')[$.inArray('2', values) != -1 ? 'show' : 'hide']();
$('.MBE')[$.inArray('3', values) != -1 ? 'show' : 'hide']();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="WBE">WBE</div>
<div class="VOBE">VOBE</div>
<div class="MBE">MBE</div>
<input id="reg" value="1,3" />
+1
source to share