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

标签 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>

最佳答案

如果您有很长的数据列表,您可以使用外部 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>

关于javascript - 尝试制作动态填充的链接选择框以在页面上显示特定图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54972321/

相关文章:

javascript - WordPress 将 && 替换为 JS &lt;script&gt; 标签中编码的 Html

php - 类型错误:$(...) 不是函数

javascript - 我可以同时在Jquery 中使用Append 和Load 功能吗?

javascript - 如何将ajax请求发送到同一页面?

javascript - 使用 jquery 从下拉列表中删除特定项目

css - 分区宽度 : auto and IE

html - 让 bootstrap col 工作

php - 在提交之前通过 Javascript 进行一些表单验证是否明智?

javascript - 自动完成 : prevent Change event after Select event

javascript - 使用 javascript 创建下拉 <select><option> 元素