order dropdown values highest at the top

Discussion in 'jQuery' started by LeeJ, Jun 3, 2014.

  1. #1
    I have a set of dropdowns being generate by jquery, but at the moment the lowest value comes out first when I need the opposite, I need in my case the value 12 to always be the one in view.

    var selects = [{
    "12": "Monthly",
    "6": "Bi-Monthly",
    "4": "Quarterly",
    "0": "N/A"
    }, {
    "12": "Monthly",
    "6": "Bi-Monthly",
    "4": "Quarterly",
    "0": "N/A"
    }, {
    "12": "Monthly",
    "6": "Bi-Monthly",
    "4": "Quarterly",
    "0": "N/A"
    }, {
    "12": "Monthly",
    "6": "Bi-Monthly",
    "4": "Quarterly",
    "0": "N/A"
    }, {
    "12": "Monthly",
    "6": "Bi-Monthly",
    "4": "Quarterly",
    "0": "N/A"
    }, {
    "12": "Monthly",
    "6": "Bi-Monthly",
    "4": "Quarterly",
    "0": "N/A"
    }, {
    "12": "Monthly",
    "6": "Bi-Monthly",
    "4": "Quarterly",
    "0": "N/A"
    }, {
    "12": "Monthly",
    "6": "Bi-Monthly",
    "4": "Quarterly",
    "0": "N/A"
    }, {
    "12": "Monthly",
    "6": "Bi-Monthly",
    "4": "Quarterly",
    "0": "N/A"
    }];
    $(function () {
    $(".addRow").click(addRow)
    })
    function sum($els) {
    var sum = 0;
    $els.each(function () {
    sum += +$(this).val()
    })
    return sum
    }
    function addRow() {
    var fieldset = $('<fieldset></fieldset>').appendTo("#test");
    var sumDiv = $("<div class='sum'>total £<span>0</span></div>").appendTo(fieldset)
    $.each(selects, function (i, v) {
    var select = $("<select name='select" + i + "'></select>").prependTo(fieldset)
    $.each(v, function (value, key) {
    $("<option></option>", {
    value: value,
    text: key
    }).appendTo(select)
    })
    select.change(function () {
    fieldset.find("span").text(sum($("select", fieldset)))
    $(".sumTotal").find("span").text(sum($("#test select")))
    }).change()
    })
    }
     
    LeeJ, Jun 3, 2014 IP
  2. ThePHPMaster

    ThePHPMaster Well-Known Member

    Messages:
    737
    Likes Received:
    52
    Best Answers:
    33
    Trophy Points:
    150
    #2
    Two things, if you want the list to be as you have in the array, switch:

    
    appendTo(select)
    
    Code (markup):
    To

    
    prependTo(select)
    
    Code (markup):
    If you want the first item selected then, you would do at the end of the addRow function:

    
    select[0].selectedIndex = 0;
    
    Code (markup):
     
    ThePHPMaster, Jul 5, 2014 IP