PDA

View Full Version : Getting the results of an array which contain certain strings



denhamd2
05-05-2011, 02:29 PM
Hi,

I have an array for all the trousers on my site. It includes the image, name, waist, description, price and buy link. The javascript I use below outputs all products in the array. What I'd like to do is only output products which contain either "Wrangler" or "Levi" in the name string AND "forty" or "thirty" in the waist string. Would anyone know how to change the for loop in order to do this?


for(i=0;i<Trousers.length;i++){
$('body').append("<div><img src='"+Trousers[i].ProductImage+"'>"+"<br /><strong>"+Trousers[i].name+"</strong><br /><span style='color: #999; font-size:10px;'>"+Trousers[i].waist+"</span><br />"+Trousers[i].description+"<br /><strong>"+Trousers[i].price+"</strong><br /><a href='"+Trousers[i].buyLink+"'>Add to Basket</a></div>");
}

Thanks in advance

midhul
05-05-2011, 03:20 PM
I guess you could add an if condition to your loop:



var TrouserName[i] = Trouser[i].name;
var TrouserWaist[i] = Trouser[i].waist;

if ( (TrouserName[i].search(/wrangler/i) != -1 || TrouserName[i].search(/levi/i != -1)) && (TrouserWaist[i].search(/forty/i) != -1 || TrouserWaist[i].search(/thirty/i) != -1) ) {

// The body append script here

}

jscheuer1
05-05-2011, 05:23 PM
Working demo:


<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript">
var Trousers = [
{ProductImage: 'some.jpg', name: 'Wrangler Loose Fit', waist: 'fortytwo', description: 'pants', price: '$20.00', buyLink: 'http//www.dynamicdrive.com/'},
{ProductImage: 'some.jpg', name: 'Levis Loose Fit', waist: 'fortytwo', description: 'pants', price: '$20.00', buyLink: 'http//www.dynamicdrive.com/'},
{ProductImage: 'some.jpg', name: 'Wrangler Straight Leg', waist: 'thirtyone', description: 'pants', price: '$20.00', buyLink: 'http//www.dynamicdrive.com/'},
{ProductImage: 'some.jpg', name: 'Wrangler Loose Fit', waist: 'twentytwo', description: 'pants', price: '$20.00', buyLink: 'http//www.dynamicdrive.com/'}
];
function appendClothing(kind, name, waist){
name = new RegExp(name, 'i'); waist = new RegExp(waist, 'i');
for(var i = 0; i < kind.length; ++i){
if(name.test(kind[i].name) && waist.test(kind[i].waist)){
$('body').append("<div><img src='"+kind[i].ProductImage+"'>"+"<br /><strong>"+kind[i].name+"</strong><br /><span style='color: #999; font-size:10px;'>"+kind[i].waist+"</span><br />"+kind[i].description+"<br /><strong>"+kind[i].price+"</strong><br /><a href='"+kind[i].buyLink+"'>Add to Basket</a></div>");
}
}
}
jQuery(function($){
$('#wrt').click(function(){
appendClothing(Trousers, 'wrangler', 'forty|thirty');
});
});
</script>
</head>
<body>
<input id="wrt" type="button" value="Wrangler Trousers - waist thirty to fortynine">
</body>
</html>