简体   繁体   English

尝试根据另一个选择框的值更改一个选择框

[英]Trying to change one select box based on the value of another

I have a small javascript program that looks at the value in one select box (id_Decade for the decade) and adjusts the range of values in two other select (range of years for that decade). 我有一个小的javascript程序,它在一个选择框中查看值(十年的id_Decade)并调整另外两个选择(该十年的年份范围)中的值范围。 The html for the page is created by a Django 2.0 application. 页面的html由Django 2.0应用程序创建。 I am running jQuery as well. 我也在运行jQuery。

One of the range of years select boxes (id_Date_year) works correctly - the decade is read from id_Decade, the range of years is created, the id_Date_year select boxes are populated correctly, and if there is a pre-selected year in id_date_year, that is preserved. 其中一个年份选择框(id_Date_year)正常工作 - 从id_Decade读取十年,创建年份范围,正确填充id_Date_year选择框,如果id_date_year中有预选年份,则为保存。

The problem the other select box, id_Approximate Date_year, does not preserve the pre-selected year value. 另一个选择框id_Approximate Date_year的问题不会保留预先选择的年份值。 The years for the decade are loaded correctly, but the pre-selected year is not selected again. 十年的年份正确加载,但未选择预选年份。

In this picture, it shows the page after loading. 在此图片中,它显示加载后的页面。 The initial decade is 1890, and the pre-selected year is 1894. Note how the Date select boxes have the year 1984 selected, but the Approximate Date boxes have Choose a year selected. 最初的十年是1890年,预选年份是1894年。请注意日期选择框如何选择1984年,但是“近似日期”框选择了“选择一年”。 Both select boxes have the correct range of years - 1890-1899. 两个选择框都有正确的年份范围 - 1890-1899。 在此输入图像描述

If I change the decade to 1950, then the Date and Approximate Date selects are correct, since the selected year is 1894, and that is not in the decade of the 1950s. 如果我将十年更改为1950年,则日期和近似日期选择是正确的,因为所选年份是1894年,并且不是在20世纪50年代的十年。 Both select boxes have the same range of years - 1950 to 1959. 两个选择框的年份范围相同 - 1950年至1959年。 在此输入图像描述

Both select boxes use the same code. 两个选择框都使用相同的代码。 I know that a space is verboten in the id name of an element, but Django is creating that id value, and I have not found a way to change it. 我知道在一个元素的id名称中有一个空格是verboten,但是Django正在创建那个id值,而我还没有找到改变它的方法。

Here is the code: 这是代码:

  (function($) {
      $(document).ready(function(){
        console.log("Made it into update years from decade");
        // Get the selected year if there is a Date field
        var Date_years = $('#id_Date_year');
        var selectedDateYear = Date_years.find(':selected').val();
        console.log("selectedDateYear="+selectedDateYear);
        // Get the decade selected
        var decade1 = $('#id_Decade option:selected').text();
        console.log("decade1="+decade1);
        // get the years for that decade
        newOptions = years_from_decade(decade1);
        // update the date select box
        update_options(newOptions, Date_years, selectedDateYear);

        // Get the selected year if there is an Approximate Date field
        var Approximate_years = $("[id='id_Approximate Date_year']");
        var selectedApproximateYear = Approximate_years.find(':selected').val();
        console.log("selectedApproximateYear="+selectedApproximateYear);
        // update the date select box
        update_options(newOptions, Approximate_years, selectedApproximateYear);

        $('#id_Decade').change(function(){
          // chang the years if the decade changes
          var decade2 = $('#id_Decade option:selected').text();
          console.log("decade2="+decade2);
          newOptions = years_from_decade(decade2);
          console.log("we have newOptions=");
          console.log(newOptions);
          update_options(newOptions, Date_years, selectedDateYear);
          update_options(newOptions, Approximate_years, selectedApproximateYear);
        })

        // calculate the years for the decade
        function years_from_decade(decade) {
          console.log("we have a decade="+decade);
          var newOptions = {};
          base_year = parseInt(decade, 10);
          for (i = 0; i < 10; i++) {
            year = base_year + i;
            key = year.toString();
            newOptions[key] = key;
          }
          return newOptions;
        }

        // replace the options with new ones
        function update_options(newOptions, target, selectedYear) {
          console.log("update_options selectedYear="+selectedYear);
          target.find('option:gt(0)').remove(); // remove all options, but not the first
          $.each(newOptions, function(key, value) {
            target.append($("<option></option>").attr("value", value).text(key));
            console.log("value="+value+" selectedYear="+selectedYear);
            if (value == selectedYear) {
              console.log("got a match! value="+value);
              target.val(value).change();
            }
          })
        }
      });
    })(jQuery);

The console messages for both select boxes are the same. 两个选择框的控制台消息都是相同的。 The matching of the pre-selected year works in both cases, but the id_Approximate Date_year select box does not get the pre-selected year selected, whereas the id_Date_year does. 在两种情况下,预选年份的匹配都有效,但id_Approximate Date_year选择框未选择预先选择的年份,而id_Date_year则选择。

Is this behavior related to the space in the id value? 这种行为是否与id值中的空格有关? As you can see from my code, I am not an experienced js coder. 从我的代码中可以看出,我不是一个经验丰富的js编码器。 I am sure there are much better ways to do what I want to do! 我相信有更好的方法可以做我想做的事情!

Thanks! 谢谢!

Mark 标记

You are correct that you can not use a space in a jQuery selector. 你是不对的,你不能在jQuery选择器中使用空格。 If this is what's causing your problem, you can get around it multiple ways: 如果这是导致您出现问题的原因,您可以通过多种方式解决问题:

  • Using plain JS and wrapping it with $() to convert it to jQuery object $(document.getElementById('id_Approximate Date_year')) 使用普通JS并用$()将其包装起来将其转换为jQuery对象$(document.getElementById('id_Approximate Date_year'))
  • Using attribute selector $("[id='content Module']") 使用属性选择器$("[id='content Module']")
  • Escaping the space $('id_Approximate\\\\ Date_year') 转义空间$('id_Approximate\\\\ Date_year')

Demo examples: 演示示例:

 $('#div one') .html('$(\\'#div one\\') Successful') $(document.getElementById('div two')) .html('$(document.getElementById(\\'div two\\')) Successful') $("[id='div three']") .html('$("[id=\\'div three\\']") Successful') $('#div\\\\ four') .html('$(\\'#div\\\\\\\\ four\\') Successful') 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="div one">Unchanged</div> <div id="div two">Unchanged</div> <div id="div three">Unchanged</div> <div id="div four">Unchanged</div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM