PDA

View Full Version : Resolved check if element is in array using jquery



ggalan
02-12-2012, 01:45 AM
i have left/right buttons, the right button pushes elements into an array.
if the user pushes the left button then pushes the right button, i want to check the right number against the array.
heres my code so far, any help would be greatly appreciated


<!DOCTYPE HTML>
<html lang="en-US">
<head>
<style type="text/css">
div{float:left; margin-right:50px;}
</style>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
var num = 0;
var arr = [];
$(function(){
$('#btn1').click(function() {
num--;
$('#rec').html(num);
return false;
});

$('#btn2').click(function() {
num++;
arr.push(num);
$('#rec').html(num);

if( jQuery.inArray(num, arr) ){// doesnt work
// do nothing
}else{
$('#arrayRec').html(arr.join(','));
}
return false;
});
});
</script>
</head>
<body>
<div id="btn1"><a href="">left</a></div>
<div id="btn2"><a href="">right</a></div>
<div id="rec">0</div>
<div id="arrayRec">null</div>
</body>
</html>

jscheuer1
02-12-2012, 03:34 AM
jQuery.inArray(item, array) returns the index of the item in the array or -1 if the item is not present. So your test:



if( jQuery.inArray(num, arr) )

should be:


if( jQuery.inArray(num, arr) > -1 )

Which will return true if the number num is in the array arr. And since it always is, nothing will ever be sent to the arrayRec div.

A better illustration of the utility of inArray might be:


<script type="text/javascript">
var num = 0;
var arr = [];
$(function(){
$('#btn1').click(function() {
num--;
$('#rec').html(num);
return false;
});

$('#btn2').click(function() {
num++;
$('#rec').html(num);

if( jQuery.inArray(num, arr) < 0 ){ // if the number isn't already in the array
arr.push(num); // put it in the array and
$('#arrayRec').html(arr.join(',')); // update the report of the array's contents
}
return false;
});
});
</script>