尝试制作动态填充的链接选择框以在页面上显示特定图像

时间:2019-03-03 18:36:38

标签: javascript jquery html css select

我正在尝试创建一个具有动态填充选择下拉列表的表单,当我选择汽车制造商然后选择汽车模型时,我可以单击“执行”按钮(我知道可以通过状态更改来完成此操作,但是我非常特别需要一个“前进”按钮)该特定汽车的图像显示在同一页面的框架中,但是我被“前进”按钮部分困住了,有人可以帮忙吗?

// object literal holding data for option elements
var Select_List_Data = {
  choices: {
    // name of associated select box

    // names match option values in controlling select box
    
    0: {
      text: ["Select Model..."],
      value: ["Select Model...", "0", "1"]
    },
    carA: {
      text: ["Select Model", "model i", "model ii", "model iii"],
      value: ["Select Model", "model i", "model ii", "model iii"]
    },
    carB: {
      text: ["Select Model", "model iv", "model v", "model vi"],
      value: ["Select Model", "model iv", "model v", "model vi"]
    },
    carC: {
      text: ["Select Model", "model vii", "model viii", "model ix"],
      value: ["Select Model", "model vii", "model viii", "model ix"]
    },
  }
};
// removes all option elements in select box
// removeGrp (optional) boolean to remove optgroups
function removeAllOptions(sel, removeGrp) {
  var len, groups, par;
  if (removeGrp) {
    groups = sel.getElementsByTagName("optgroup");
    len = groups.length;
    for (var i = len; i; i--) {
      sel.removeChild(groups[i - 1]);
    }
  }

  len = sel.options.length;
  for (var i = len; i; i--) {
    par = sel.options[i - 1].parentNode;
    par.removeChild(sel.options[i - 1]);
  }
}

function appendDataToSelect(sel, obj) {
  var f = document.createDocumentFragment();
  var labels = [],
    group,
    opts;

  function addOptions(obj) {
    var f = document.createDocumentFragment();
    var o;

    for (var i = 0, len = obj.text.length; i < len; i++) {
      o = document.createElement("option");
      o.appendChild(document.createTextNode(obj.text[i]));

      if (obj.value) {
        o.value = obj.value[i];
      }

      f.appendChild(o);
    }
    return f;
  }

  if (obj.text) {
    opts = addOptions(obj);
    f.appendChild(opts);
  } else {
    for (var prop in obj) {
      if (obj.hasOwnProperty(prop)) {
        labels.push(prop);
      }
    }

    for (var i = 0, len = labels.length; i < len; i++) {
      group = document.createElement("optgroup");
      group.label = labels[i];
      f.appendChild(group);
      opts = addOptions(obj[labels[i]]);
      group.appendChild(opts);
    }
  }
  sel.appendChild(f);
}
// anonymous function assigned to onchange event of controlling select box
document.forms["demoForm"].elements["category"].onchange = function(e) {
  // name of associated select box
  var relName = "choices";

  // reference to associated select box
  var relList = this.form.elements[relName];

  // get data from object literal based on selection in controlling select box (this.value)
  var obj = Select_List_Data[relName][this.value];

  // remove current option elements
  removeAllOptions(relList, true);

  // call function to add optgroup/option elements
  // pass reference to associated select box and data for new options
  appendDataToSelect(relList, obj);
};

// populate associated select box as page loads
(function() {
  // immediate function to avoid globals

  var form = document.forms["demoForm"];

  // reference to controlling select box
  var sel = form.elements["category"];
  sel.selectedIndex = 0;

  // name of associated select box
  var relName = "choices";
  // reference to associated select box
  var rel = form.elements[relName];

  // get data for associated select box passing its name
  // and value of selected in controlling select box
  var data = Select_List_Data[relName][sel.value];

  // add options to associated select box
  appendDataToSelect(rel, data);
})();
<form action="#" method="post" id="demoForm" class="demoForm">

        <label class="wrapper" for="states">Target Manufacturer</label>
    <div class="button dropdown"> 
        <select name="category">
          <option value="0" selected="selected">Select a Manufacturer...</option>
<option value="carA">car a</option>
<option value="carB">car b</option>
<option value="carC">car c</option>
        </select>  </div>
<div><label class="wrapper" for="states">Model</label>
       <div class="button dropdown">  <select name="choices" id="choices">
            <!-- populated using JavaScript -->
        </select></div>

1 个答案:

答案 0 :(得分:0)

如果数据列表很长,则可以使用外部json文件,但是如果要在短列表之间进行更改,则可以使用数组来填充选择选项。 您可以使用简短的jquery函数来获取所选(已过滤)选项,并根据所选内容显示该图像。

我包括代码(带有占位符图像)和一个fiddle

(我刚刚意识到我在发布时没有考虑到代码中的一个小故障-但是您可以解决它-[onchange]在第一个选项上不起作用。对selectedindex的检查将对其进行排序!)

仅出于演示目的填充福特选项。

希望这会有所帮助

$(document).ready(function() {
  //init data
  var arrayList = [{
      "Id": 0,
      "Name": "Please select an option"
    },
    {
      "Id": 1,
      "Name": "Ford"
    },
    {
      "Id": 2,
      "Name": "Jaguar"
    },
    {
      "Id": 3,
      "Name": "VW"
    }
  ];


  for (var i = 0; i <= arrayList.length; i++) {
    $('#choices').append('<option value="' + arrayList[i].Id + '">' + arrayList[i].Name + '</option>');
  }


});

$("#choices").change(function() {
  // $.getJSON("jsondata/data.json", function(data) {
  //use this if using external json sets
  
  var $selection = $("#choices option:selected");
  var key = $selection.val();

  var vals = [];
  
  $(".imghere").attr("src", "");

  switch (key) {
    case '1':
      vals = ["Fiesta", "Focus", " Mustang"]; //you can list your values in arrays if you want e.g. vals=["Fiesta", "Focus", "Mustang"] but if you have a lot of values, then it may be easier to read values in from an external file
      break;
    case '2':
      vals = ["I don't own a Jag"] //data.Jaguar.split(",");
      break;
    case '3':
      vals = ["5-series", "7-series"] //data.VW.split(",");
      break;
    case '0':
      vals = ['Please choose a category'];
  }

  var $secondChoice = $("#filter");
  $secondChoice.empty();
  $.each(vals, function(index, value) {
    $secondChoice.append("<option>" + value + "</option>");
  });

});


$("#filter").change(function() {
  var $filter = $("#filter option:selected").val();
  var baseurl = "https://www.yourdomain.com/images/";
  var $showimg = baseurl + $filter + ".jpg";
  //$(".imghere").attr("src",$showimg); use this, the next line is demo purposes
  $(".imghere").attr("src", "https://static1.squarespace.com/static/5a6def0aace864bfafe27afe/t/5a6e72bc085229bac52f23be/1518455566354/Fiesta.jpg"); /*use variable in place of the placeholder image*/

});
body {
  height: 100vh;
}

h4 {
  margin: 5px 0px;
  padding: 0px;
}

#choices,
#filter {
  margin-bottom: 9px;
  width: 200px;
  display: block;
}

#imagehere {
  position: absolute;
  display: block;
  margin-top: 20px;
  margin-left: 50px;
  top: 40vh;
  width: 250px;
  height: 250px;
  border: 1px dashed grey;
}

.imghere {
  opacity: 1;
  width:225px;
  height:auto;
  z-index: 10;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h4>
  Category
</h4>
<select id="choices">

</select>

<h4>
  Filter
</h4>
<select id="filter">

</select>

<div id="imagehere">
  <img class="imghere" src="" alt="filtered category">

</div>