I have one array like this.
var myArray = ["1", "2", "3", "4", "5"];
I need to find the next element when I click next. Suppose I've 2 in a variable, when I click "next" button, I need to check the array and get 3 and so on.
jQuery:
You should use .inArray() with modulus operator:
var myArray = ["1", "2", "3", "4", "5"];
var val = "2";
var next = myArray[($.inArray(val, myArray) + 1) % myArray.length];
JavaScript:
var myArray = ["1", "2", "3", "4", "5"];
var val = "2";
var index = myArray.indexOf(val);
if(index >= 0 && index < myArray.length - 1){
var next = myArray[index + 1];
alert(next);
}
undefined if you use modulus it will go back to first element. Hope this helps you :)<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" value="next" id="next">
<script>
var globle = 0; // by default first page
var myArray = ["1", "2", "3", "4", "5"];
$(document).ready(function(){
$("#next").click(function(){
if(globle == myArray.length){
globle = 0;
}
alert(myArray[globle]);
globle++;
});
});
</script>
Try this:
var myArray = ["1", "2", "3", "4", "5"];
var val = "2";
function checknext() {
var next = $.inArray(val, myArray) + 1;
if (next < myArray.length) {
val = myArray[next];
alert(val);
}
else {
alert("No More Item Exist");
}
}
function checkprv() {
var prv = $.inArray(val, myArray) - 1;
if (prv >= 0) {
val = myArray[prv];
alert(val);
}
else {
alert("No More Item Exist");
}
loop??myArray[var]?