Choose option from select list using next/previous button with jquery

前端 未结 4 632
礼貌的吻别
礼貌的吻别 2021-01-20 00:48

What is best way to navigate select option using next/previous button with jquery? I have a select list when change also changes some div. Instead of just a dropdown, I want

4条回答
  •  死守一世寂寞
    2021-01-20 01:38

    Description

    You can use jQuery's .removeAttr(), attr(), .next() and .prev() methods for that.

    Check out my sample and this jsFiddle Demonstration

    Sample

    $("#next").click(function() {
      var nextElement = $('#mycars > option:selected').next('option');
      if (nextElement.length > 0) {
        $('#mycars > option:selected').removeAttr('selected').next('option').attr('selected', 'selected');
      }
    });
    
    $("#prev").click(function() {
      var nextElement = $('#mycars > option:selected').prev('option');
      if (nextElement.length > 0) {
        $('#mycars > option:selected').removeAttr('selected').prev('option').attr('selected', 'selected');
      }
    });
    

    More Information

    • jQuery.removeAttr()
    • jQuery.attr()
    • jQuery.next()
    • jQuery.prev()

    Update

    I don't know if you want to disable the, for example, next button if the last element is selected, select the first one or do nothing. Please provide this information.

    You can do this to go to this to go to the first element if the last is selected, or to the last if first is selected.

    $("#next").click(function() {
        var isLastElementSelected = $('#mycars > option:selected').index() == $('#mycars > option').length -1;
    
        if (!isLastElementSelected) {     
            $('#mycars > option:selected').removeAttr('selected').next('option').attr('selected', 'selected'); 
        } else {
               $('#mycars > option:selected').removeAttr('selected');
               $('#mycars > option').first().attr('selected', 'selected'); 
         }   
    });
    
    $("#prev").click(function() {
        var isFirstElementSelected = $('#mycars > option:selected').index() == 0;
    
        if (!isFirstElementSelected) {
           $('#mycars > option:selected').removeAttr('selected').prev('option').attr('selected', 'selected');
        } else {
             $('#mycars > option:selected').removeAttr('selected');
             $('#mycars > option').last().attr('selected', 'selected'); 
        }
    
    });
    

    Updated jsFiddle

提交回复
热议问题