Ad

Javascript For Pagination

- 1 answer

I'm new with javascript. I have a problem with my code. Hope someone can help me.

I make 2 buttons and 1 dropdown. 2 Buttons are Btn-Next and Btn-Previous. And dropdown is Page when Btn-Next click, Page will increase + 1 (ex: default 1, When clicked will be 2). And When btn-previous click, Page will decrease -1 (ex: default 2, When cicked will be 1).

And the problem is when I change the dropdown and try to click 1 button. The option is false.

Btn Next:

$("#btn-next").on('click', function () {

    var datahalaman = $("#halaman").val();

    $(".pagetotal").find("option[value ='" + datahalaman + "']").removeAttr('selected');

    var inchalaman = parseFloat(datahalaman) + 1;

    var datahalamanbaru = $("#halaman").val(inchalaman);

    var halamannext = inchalaman + 1;

    var tek = datahalamanbaru.val();

    $(".pagetotal").find("option[value ='" + tek + "']").attr('selected', 'selected');

})

Btn previous:

$("#btn-previous").on('click', function () {

    var datahalaman = $("#halaman").val();

    $(".pagetotal").find("option[value ='" + datahalaman +"']").removeAttr('selected');

    var inchalaman = parseFloat(datahalaman) - 1;

    var datahalamanbaru = $("#halaman").val(inchalaman);

    var tek = datahalamanbaru.val();

    $(".pagetotal").find("option[value ='" + tek + "']").attr('selected', 'selected');

})

Dropdown:

$(document).on('change', '#pagetotal', function () {

    var optionSelected = $("option:selected", this);

    var valueSelected = this.value;

    var datahalaman = $("#halaman").val();

    $(".pagetotal").find("option[value ='" + datahalaman + "']").removeAttr('selected');

    var fix =$("#halaman").val(valueSelected)

    var fix = $("#pagetotal").find("option[value ='" + fix.val()+"']").attr('selected', 'selected');

})
Ad

Answer

In this we need to check every click and change of the elements we have, Also created a fiddle for this exact requirement: https://jsfiddle.net/rt7dmoL5/3/

Try the following code to fix the issue:

  $(".selectpage").on("change",function(){
    validateSelectedPrev();
  });
var validateSelectedPrev = function(){
  var selectedValue =$(".selectpage").prop('selectedIndex');
  if(selectedValue == 0){
    $(".prev").attr("disabled","true");
  }else{
    $(".prev").removeAttr("disabled");
  }

  if($(".selectpage").prop('selectedIndex') == ($(".selectpage option").length-1)){
    $(".next").attr("disabled","true");
  }else{
    $(".next").removeAttr("disabled");
  }
}
  validateSelectedPrev();
$(".prev").click(function(){
    var selectedInd  =$(".selectpage").prop('selectedIndex');
    $(".selectpage").val($(".selectpage option").eq(selectedInd-1).val());
    validateSelectedPrev();
  });
  $(".next").click(function(){
     var selectedInd  =$(".selectpage").prop('selectedIndex');
     $(".selectpage").val($(".selectpage option").eq(selectedInd+1).val());
     validateSelectedPrev();
  });
Ad
source: stackoverflow.com
Ad