Reputation: 1389
I'm trying to set a classname on a list item based on if the value is in an array. The problem I'm facing now is that my code returns just one classname instead of several. I'm a bit stuck now.
What I do is getting some data from JSON. That data is a string that needs to be seperated by a comma. Those seperate values are in an array called usp
.
Next I want to test all those values if they contain some text. If that's the case then create a classname based on the value.
To clarify:
First I get some JSON data which returns a string:
'Type 1,1 fase,16 ampere,4 to 8 meter,next day delivery'
Next I split that data, like so:
var usp = productUsps.split(',');
// returns: [ "Type 1", "1 fase", "16 ampere", "4 to 8 meter", "next day delivery" ]
Now I want to test if all those values contain a piece of text and if they match then set a class name, like so:
// create icon classes based on usp title
var className = '',
reLength = new RegExp('meter' , "i" ),
reType = new RegExp('type' , "i" ),
reFase = new RegExp('fase' , "i"),
reShip = new RegExp('delivery' , "i" ),
reAmpere = new RegExp('ampere' , "i" );
usp.forEach(function(item) {
if( $.inArray(reLength, usp) ){
className = 'icon-length';
} else if ( $.inArray(reType, usp)){
className = 'icon-type';
} etc....
uspHtml.push('<li><i class="bullit '+className+'"></i>'+item+'</li>');
});
Whatever I try my code only returns just one class name, for example ìcon-length
.
I also tried to test like this:
if (reFase.test(usp) )
className = 'icon-fase';
else if (reShip.test(usp))
className = 'icon-ship';
// etc etc....
What I'm I doing wrong? Or is there a better way to accomplish this? Any help greatly appreciated!!
Complete code:
$.getJSON(url, function(data){
if(data.data_02){
var productUsps = data.data_02;
var usp = productUsps.split(',');
// create icons classes based on usp title
var className = '',
reLength = new RegExp( getAjaxTranslation('meter') , "i" ),
reType = new RegExp( getAjaxTranslation('type') , "i" ),
reFase = new RegExp( getAjaxTranslation('fase') , "i"),
reShip = new RegExp( getAjaxTranslation('delivery') , "i" ),
reAmpere = new RegExp( getAjaxTranslation('ampere') , "i" );
usp.forEach(function(item) {
if( $.inArray(reLength, usp) ){
className = 'icon-length';
} else if ( $.inArray(reType, usp)){
className = 'icon-type';
} .... etc ....
uspHtml.push('<li><i class="bullit '+className+'"></i>'+item+'</li>');
});
uspHtml = uspHtml.join('');
} else {
return;
}
}).done(function(){
$this.find('.product-usps ul').html(uspHtml);
setTimeout(function(){ $('.product-usps .loader').hide() }, 500);
});
Upvotes: 0
Views: 312
Reputation: 447
You're using
$.inArray(reLength, usp)
This will always be true as you're checking in the whole array.
Try this instead:
usp.forEach(function(item) {
if (reLength.test(item)){
className = 'icon-length';
} else if (reType.test(item)){
className = 'icon-type';
} etc....
Upvotes: 1