级联数据选择使用JSON数据使用javascript创建Dropdown

时间:2017-01-04 01:14:36

标签: javascript html json

我正在尝试使用java脚本创建级联数据表,但它不能正确打印数据。 当我从下拉列表中选择资产时,我想克里特下拉,它从该资产中加载所有部分名称,当我从他们的子项中选择部分时,它选择超声波部分名称。 同样在资产中,它填充了4次“资产4”。它应该只打印一次。 我试图去除它,但它不起作用。任何人都可以帮助我吗?

我想只在JavaScript中执行此操作 JAVASCRIPT

var stateObject = '{"uri": "/assets/4afd3544-cea1-363d-ba29    e39831d8930d","name": "Asset 4","sections": [{"uri": "/assets/2dc11152-7b85-   35d7-8af6-c48ca4397d9f","sectionId": null, "name": "Section    1","ultrasonicSensors": null,"temperatureSensors":   null,"ultrasonicSensorPositions": [{"ultrasonicSensorPositionId":"1395","sensorPositionName":"MeasurementPosition 1","diameter": "0","rotation": "0","sequenceNumber": null,  "sectionId": "/assets/2dc11152-7b85-35d7-8af6-c48ca4397d9f"}]}]}';

  var json = JSON.parse(stateObject);

window.onload = function () {
var stateSel = document.getElementById("stateSel"),
    countySel = document.getElementById("countySel"),
    citySel = document.getElementById("citySel");

for (state in json) {
 stateSel.options[stateSel.options.length] = new Option(json.name , "");

}

stateSel.onchange = function () {
    countySel.length = 1; // remove all options bar first
    citySel.length = 1; // remove all options bar first
    if (this.selectedIndex < 1) {
      countySel.options[0].text = "Please select state first"
      citySel.options[0].text = "Please select county first"
      return; // done   
    }  
    countySel.options[0].text = "Please select county"
    var x = JSON.stringify(json.sections);

   // alert(x)

    for (var county in x) {

    countySel.options[countySel.options.length] = new Option(county, x);
    }
    if (countySel.options.length==2) {
      countySel.selectedIndex=1;
      countySel.onchange();


    }  

}

stateSel.onchange(); // reset in case page is reloaded

countySel.onchange = function () {
    citySel.length = 1; // remove all options bar first
    if (this.selectedIndex < 1) {
      citySel.options[0].text = "Please select county first"
      return; // done   
    }  
    citySel.options[0].text = "Please select city"

    var cities = stateObject[stateSel.value][this.value];
    for (var i = 0; i < cities.length; i++) {
        citySel.options[citySel.options.length] = new Option(cities[i], cities[i]);
    }
    if (citySel.options.length==2) {
      citySel.selectedIndex=1;
      citySel.onchange();
    }
}
 }

这是js fiddle demo

0 个答案:

没有答案