首页 > 解决方案 > 带有转到网址按钮的条件下拉框?

问题描述

我正在我的网站上设置一个页面,该页面有2 个下拉框,第二个是从第一个下拉框中的选定选项填充的。

我的代码运行完美,但是我无法go在第二个下拉框中找到按钮来调用URL要转到的选定值。

如何Find Course从下拉框 2 中获取用于调用所选选项中的 URL 的按钮?

这是我的代码的演示!

任何帮助将不胜感激:) 我对 JavaScript 和高级 HTML 非常陌生。

HTML

    <div id="myQuestions">
        <select id="QuestionOptions">
            <option value="Aa">Choose a Faculty</option>
            <option value="Ba">Faculty 1</option>
            <option value="Ca">Faculty 2</option>
        </select>
    </div>
    <div id="myAnswers">
        <div id="Aa" style="display: Aa;">
            <div id="F1">
                <select id="F1answers">
                    <option value="A1">Course Selection</option>
                </select>
            </div>
        </div>
        <div id="Ba" style="display: none;">
            <div id="F2">
                                <select id="F2answers">
                    <option value="URL 1 GOES HERE">Course 1</option>
                    <option value="URL 2 GOES HERE">Course 2</option>
                </select>
            </div>
        </div>
        <div id="Ca" style="display: none;">
            <div id="F3">
                <select id="F3answers">
                    <option value="URL 3 GOES HERE">Course 3</option>
                </select>
            </div>
        </div>
    </div>

<div class="FindCourse">
    <a id="CourseGo" href="HOMEPAGE URL"> Find Course </a>
</div>

JS

$(function () {
    $('#QuestionOptions').change(function () {
        $('#myAnswers > div').hide();
        $('#myAnswers').find('#' + $(this).val()).show();

});
});
var sel = document.getElementById('myAnswers');
sel.onchange = function () {
    document.getElementById("CourseGo").href = this.value;
}

标签: javascripthtml

解决方案


您不应将属性 id用于多个元素,但是此脚本将根据您的逻辑工作:

const $myAnswersDiv = $("#myAnswers > div");
const $courseGo = $("#CourseGo");
const $myAnswers = $("#myAnswers");

$(function() {
  $("#QuestionOptions").change(function() {
    $myAnswersDiv.hide();
    $myAnswers.find("#" + $(this).val()).show();

    // targeting (#myAnswers > div > select) without style="display: none"
    let $selectVisible = $myAnswersDiv
      .not('[style$="display: none;"]')
      .find("select");

    // setting the current value of select to <a id="CourseGo">
    $courseGo.attr("href", $($selectVisible).val());

    // listener on the current <select> to set value to <a id="CourseGo">
    $selectVisible.change(function() {
      $courseGo.attr("href", $(this).val());
    });
  });
});

推荐阅读