2013-09-05 3 views
2

Я создал следующий код, и теперь я хочу добавить значение внутри опции выбора. В то же время я не получаю значение во всех там, где выпадаете. Например, вы можете установить значение параметра, чтобы помочь мне.Как добавить значение из опции выбора с массивом

Я создал массив, как таким образом:

var d = new Array("Any","D01 Boat Quay/Raffles Place","D02 Chinatown/Tanjong Pagar","D03 Alexandra/Commonwealth","D04 Harbourfront/Telok Blangah"); 
var options = ''; 

for (var i = 0; i < d.length; i++) { 
    options += '<option>' + d[i] + '</option>'; 
} 
$("#TypeList1").html(options); 
sb2.sync(); 

Я попытался с этим кодом:

var dd = { 
      Any : 'Any', 
      1 : 'D01 Boat Quay/Raffles Place', 
      2 : 'D02 Chinatown/Tanjong Pagar', 
      36 : 'D03 Alexandra/Commonwealth', 
      37 : 'D04 Harbourfront/Telok Blangah', 
      38 : 'D05 Buona Vista/West Coast' 
     }; 

     var select = document.getElementById("TypeList1"); 
     for(index in dd) { 
      select.options[select.options.length] = new Option(dd[index], index); 
     } 

МОЙ КОД:

<!doctype html> 
<html> 
<head> 
<title>Custom Styled Selectbox</title> 
<link rel="stylesheet" href="http://www.roblaplaca.com/docs/custom-selectbox/css/customSelectBox.css" /> 
<!--<link rel="stylesheet" href="customSelectBox.css" />--> 
</head> 
<body class="noJS"> 
<script type="text/javascript"> 
try{Typekit.load();}catch(e){} 
    var bodyTag = document.getElementsByTagName("body")[0]; 
    bodyTag.className = bodyTag.className.replace("noJS", "hasJS"); 
</script> 
<style type="text/css"> 
.hasJS select.custom1 { 
    position: absolute; 
    left: -999em; 
} 
</style> 
<div class="grid-system clearfix"> 
    <div class="row"> 
     <div class="col span-9"> 
      <div class="example clearfix"> 
       <select class="custom interactive" id="properties"> 
        <!--<option value="selectone">Select a Type</option>--> 
        <option value="One" selected>One</option> 
        <option value="Two">Two</option> 
        <option value="Three">Three</option> 
        <option value="Four">Four</option> 
       </select> 

       <select class="custom interactive" id="TypeList"> 
        <option selected>Any</option> 
        <option>Two</option> 
        <option>Three</option> 
        <option>Four</option> 
       </select> 

       <select class="custom1 interactive1" id="TypeList1"> 

       </select> 
      </div> 
     </div> 
    </div> 
</div> 

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> 
<script src="http://github.com/vitch/jScrollPane/raw/master/script/jquery.jscrollpane.js"></script> 
<script src="http://www.roblaplaca.com/docs/custom-selectbox/js/SelectBox.js"></script> 
<!--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> 
<script src="jquery.jscrollpane.js"></script> 
<script src="SelectBox.js"></script> --> 
<script type="text/javascript"> 
$(function() { 
    window.prettyPrint && prettyPrint() 
    /* 
     This is how initialization normally looks. 
     Typically it's just $("select.custom"), but to make this example more clear 
     I'm breaking from the pattern and excluding interactive 
    */ 
    var sb, sb2; 
    $("select.custom").not(".interactive").each(function() { 
     sb = new SelectBox({ 
      selectbox: $(this), 
      height: 150, 
      width: 200 
     }); 
    }); 

    $("select.custom1").not(".interactive").each(function() { 
     sb2 = new SelectBox({ 
      selectbox: $(this), 
      height: 150, 
      width: 250 
     }); 
    }); 

    /* 
     Adding some extra functionality for "interactive" selects 
    */ 
    var TypeList = { 
     //selectone: ["Any"], 
     'One': ["Any", "Landed", "Condominium", "HDB", "Others"], 
     'Two': ["Any", "Landed", "Condominium", "HDB", "Others"], 
     'Three': ["Any", "Industrial", "Retail", "Land", "Office", "Others"], 
     'Four': ["Any", "Industrial", "Retail", "Land", "Office", "Others"] 
     } 

    var defaultSelectboxSettings = { 
     height: 150, 
     width: 150 
    }; 

    var country_SB = null, 
    city_SB = null; 

    $("select.interactive").each(function() { 
     if ($(this).attr("id") == "properties") { 
      country_SB = new SelectBox($.extend(defaultSelectboxSettings, { 
       selectbox: $(this), 
       changeCallback: function(val) { 
        if (TypeList[val]) { 
         city_SB.enable(); 
         updateCities(val); 
        } 
        if (val == "selectone") { 
         city_SB.disable(); 
        } 

        <!------------------------------Code By Me----------------------------> 
        var getType = jQuery("#TypeList option:selected").text(); 
        if(getType == "HDB"){ 

         var e = new Array("Any","Boat Quay","Chinatown","Havelock Road","Marina Square"); 
         var options = ''; 

         for (var i = 0; i < e.length; i++) { 
          options += '<option>' + e[i] + '</option>'; 
         } 
         $("#TypeList1").html(options); 
         sb2.sync(); 

        }else{ 

         var d = new Array("Any","D01 Boat Quay/Raffles Place","D02 Chinatown/Tanjong Pagar","D03 Alexandra/Commonwealth","D04 Harbourfront/Telok Blangah"); 
         var options = ''; 

         for (var i = 0; i < d.length; i++) { 
          options += '<option>' + d[i] + '</option>'; 
         } 
         $("#TypeList1").html(options); 
         sb2.sync(); 

        } 
        <!------------------------------Code By Me----------------------------> 

       } 
      })); 
     } else if ($(this).attr("id") === "TypeList") { 
      city_SB = new SelectBox($.extend(defaultSelectboxSettings, { 
       selectbox: $(this) 
       })); 
     } 


     //if(jQuery("#properties option:selected").text()) 
    }); 

    updateCities($("#properties").val()); 

    if ($("#properties").val() == "selectone") { 
     //city_SB.disable(); 
    } 

    <!------------------------------Code By Me----------------------------> 
    if(jQuery("#TypeList option:selected").text()){ 

     var dd = new Array("Any","D01 Boat Quay/Raffles Place","D02 Chinatown/Tanjong Pagar","D03 Alexandra/Commonwealth","D04 Harbourfront/Telok Blangah"); 
     var options = ''; 

     for (var i = 0; i < dd.length; i++) { 
      options += '<option>' + dd[i] + '</option>'; 
     } 
     $("#TypeList1").html(options); 
     sb2.sync(); 

    } 
    <!------------------------------Code By Me----------------------------> 

    function updateCities(val) { 
     var $select = $("select#TypeList"), 
     html = ""; 

     for (var i = 0; i < TypeList[val].length; i++) { 
      html += '<option value="' + TypeList[val][i] + '">' + TypeList[val][i] + '</option>'; 
     } 
     $select.html(html); 

     // HACK: chrome is too fast? 
     setTimeout(function() { 
      city_SB.sync(); 
     }, 1); 
    } 

});   
</script> 
</body> 
</html> 

Любые идеи или предложения? Благодарю.

ответ

3

ваш массив может выглядеть следующим образом

var options = [{ 
    option: option1, 
    value: value1 
}, { 
    option: option2, 
    value: value2 
}]; 

Вы затем цикл над этим JSon массив как так

for (var i = 0; i < options.length; i++) { 
    var option = options[i]; 
} 

и изменить эту строку

options += '<option>' + d[i] + '</option>'; 

к (добавить это в цикл цикла)

options += '<option value="' + d.value + '">' + d.option + '</option>'; 
+0

но как определить в массиве? – Manan

+0

like {"text": "Вариант 1", "значение": "Значение 1"} – Manan

+0

@Manan позволяет мне обновлять свой ответ, не был уверен в том, каков был фактический вопрос, но да, ваш второй комментарий будет работать – Johan

0

Выполните следующие действия:

Подготовить объект JSON следующим образом:

var data = [ 
    { 
    "id": "id1", 
    "name": "name1"}, 
{ 
    "id": "id2", 
    "name": "name2"} 
]; 

Затем подготовить список опций следующим образом:

$.each(data, function(i, option) { 
    $('#sel').append($('<option/>').attr("value", option.id).text(option.name)); 
}); 
Смежные вопросы