0

I have array which holds option values from select.

var arrValues = new Array();
$("#myId option").each(function()
{
    var sel = $("#myId").val();
    arrValues.push(sel);
} 

now I want to find current selected value from #myId select option and take next array index value.

forexample if array contains values like

array = "AB", "CD", "EF"

if my currently selected value is AB I want to take CD value and store into var nextValue variable.

1
  • You want this to happen every time you select an item from the select drop down? Commented Jun 25, 2014 at 9:22

3 Answers 3

1

This is how you would do it:

D E M O

var curval, nextval, _index, arrValues = new Array();

$(function() { bindDropdown();});
function bindDropdown() {
   $("#myselect option").each(function()
    {
        arrValues.push($(this).val());
    });
    $("#myselect").on('change', function() {
        curval = $( "#myselect" ).val();
        _index = $.inArray(curval, arrValues);
        nextval = arrValues[(_index==arrValues.length-1) ? 0 : _index+1];
    }); 
}

nextval will be your next value..

Notice: if you choose the last option, then your next becomes the first.. I don't know if that's your desired behavior so let me know..

Sign up to request clarification or add additional context in comments.

Comments

0

following function returns the next value or an empty string if the current value is the last value:

function getNextValue(array, currentValue) {
    var nextValue = "";
    for(var i = 0; i < array.length - 1; i++) {
        if(array[i] == currentValue) {
            nextValue = array[i + 1];
            break;
        }
    }
    return nextValue;
}

Comments

0

You can use Array.prototype.indexOf to find the index in the array, then just increment it to get the next. Be careful if the last option is selected, because there is no next value.

var nextValue;
var index = arrValues.indexOf($('#myId').val());
if(index < arrValues.length-1){
    nextValue = arrValues[index+1];
} else {
    // the selected value is the last in the array so can't get next
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.