pshoeg
pshoeg

Reputation: 389

Add number range to select options

I have a select looking something like this:

<select id="address">
  <option noodd="1-9" noeven="2-6">Address Name 1</option>
  <option noodd="3-5" noeven="2-10">Address Name 2</option>
  <option noodd="3-11" noeven="1-5">Address Name 3</option>
</select>

<select id="housenumber">
</select>

Whenever one of the options in #address is selected, I need #housenumber to be filled with the numbers within the ranges of the address selected. So when Address Name 1 is selected, I need #housenumber to look like this:

<select id="housenumber">
  <option>1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
  <option>5</option>
  <option>6</option>
  <option>7</option>
  <option>9</option>
</select>

Does anyone have a clever idea how to do that?

UPDATE, what I need is this:

Upvotes: 0

Views: 1312

Answers (1)

Jamiec
Jamiec

Reputation: 136154

Something like this should do it:

$('#address').change(function(){
    var $selected = $('option:selected',this);
    var odd = $selected.attr('noodd').split('-');
    var even = $selected.attr('noeven').split('-');

    var arr = [];
    for(var o = parseInt(odd[0],10);o<=parseInt(odd[1],10);o+=2){
       arr.push(o);  
    }

    for(var e = parseInt(even[0],10);e<=parseInt(even[1],10);e+=2){
       arr.push(e);  
    }

    var $housenumber = $('#housenumber');
    $housenumber.empty();
    $.each(arr.sort(function(a,b){return a-b;}),function(i,e){
       $housenumber.append($('<option/>').text(e));
    });
});

Live example: http://jsfiddle.net/uhwMS/

A couple of notes:

  1. You should use data-* attributes rather than custom ones. Making your option nodes look like <option data-odd="1-9" data-even="2-6">Address Name 1</option> making reading them safer, eg var odd = $selected.data('odd').split('-');

  2. Your third element has odd numbers for even, giving some strange results. Assume this was just ann error posting the question?

Upvotes: 2

Related Questions