VIKASKUMAR SHANSETI VIKASKUMAR SHANSETI - 8 days ago 4
Javascript Question

How to autochage the dropdown option for every 30 sec

I have done the dropdown with the previous and next.
I want to know how can I change the dropdown option value automatically for every n seconds.
https://jsfiddle.net/wmwayysz/

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<button type="button" id="prev">Previous</button>
<select id="selectBox" onchange="currentSlide(value);" class="selectpicker">
<option value="1" class="options">Electronics</option>
<option value="2" class="options">Clothing</option>
<option value="3" class="options">Health</option>
<option value="4" class="options">Food</option>
<option value="5" class="options">Travel</option>
<option value="6" class="options">Mobiles</option>
<option value="7" class="options">Grocery</option>
<option value="8" class="options">Recharge</option>
<option value="9" class="options">Furniture</option>




Next

$.fn.loopNext = function(selector) {
var selector = selector || '';
return this.next(selector).length ? this.next(selector) :
this.siblings(selector).addBack(selector).first();
}
$.fn.loopPrev = function(selector) {
var selector = selector || '';
return this.prev(selector).length ? this.prev(selector) :
this.siblings(selector).addBack(selector).last();
}
$("#next").click(function() {
$('#selectBox > option:selected')
.removeAttr('selected')
.loopNext('option')
.prop('selected', 'selected');
});

$("#prev").click(function() {
$('#selectBox > option:selected')
.removeAttr('selected')
.loopPrev('option')
.prop('selected', 'selected');
});

function currentSlide(selectionValue) {
console.log(selectionValue);
}

Answer

You have to call the same iteration of code after some time interval which you are using on next. So the common code goes into function. Here is the fiddle for it. https://jsfiddle.net/wmwayysz/2/

Here is Your javascript updated code

$.fn.loopNext = function(selector) {
  var selector = selector || '';
  return this.next(selector).length ? this.next(selector) : this.siblings(selector).addBack(selector).first();
}
$.fn.loopPrev = function(selector) {
  var selector = selector || '';
  return this.prev(selector).length ? this.prev(selector) : this.siblings(selector).addBack(selector).last();
}
$("#next").click(funShowNext);
setInterval(funShowNext,3000);

function funShowNext() {
  $('#selectBox > option:selected')
    .removeAttr('selected')
    .loopNext('option')
        .prop('selected', 'selected');
}

$("#prev").click(function() {
  $('#selectBox > option:selected')
    .removeAttr('selected')
    .loopPrev('option')
        .prop('selected', 'selected');
});

function currentSlide(selectionValue) {
  console.log(selectionValue);
}