Javascript 未捕获的类型错误:无法读取 HTML 选择的 null 属性“选项”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44516034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:34:50  来源:igfitidea点击:

Uncaught TypeError: Cannot read property 'options' of null for HTML select

javascriptjqueryhtmlforms

提问by mistaq

In my form I have two select inputs, in which the second select changing its values depending on the first select input.

在我的表单中,我有两个选择输入,其中第二个选择根据第一个选择输入更改其值。

However, when selecting a value in the first select input, the second select input fails to update its values accordingly. I get the error:

但是,当在第一个选择输入中选择一个值时,第二个选择输入无法相应地更新其值。我收到错误:

Uncaught TypeError: Cannot read property 'options' of null
    at newchangeCategory (managefood:340)
    at HTMLSelectElement.onchange (managefood:273)
Uncaught TypeError: Cannot read property 'options' of null
    at newchangeCategory (managefood:340)
    at HTMLSelectElement.onchange (managefood:273)

Below is the code for the form, as well as the script that changes the second select input based on what is given in the first. I've commented in the code which lines the error above refer to.

下面是表单的代码,以及根据第一个中给出的内容更改第二个选择输入的脚本。我已经在代码中注释了上面提到的错误。

<div class="modal fade" id="newfoodModal" tabindex="-1" role="dialog" aria-labelledby="newfoodLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">

                     <span aria-hidden="true">&times;</span>
                    </button>
        <h3 class="modal-title" id="newfoodLabel">New Food</h3>
        <br>
        <div>
          <div class="col-sm-12">
            <label for="category" id="newCategoryLabel" style="text-align: left">Category</label>
            <select name="category" id="newCategory" onchange="newchangeCategory()" class="form-control"> //line 273
                                <option value="" disabled selected hidden>Select a category</option>
                                <option value="Fruit">Fruit</option>
                                <option value="Vegetable">Vegetable</option>
                            </select>
          </div>
          <div class="col-sm-12">
            <label for="type" id="newtypeLabel" style="text-align: left">Type</label>
            <select name="type" id="newtype" class="form-control"></select>
          </div>

          //this script enables for the second select to change based on the first - if Fruit is chosen as the category for example, only fruit options are shown in the Type select.
          <script type="text/javascript">
            var typeOptions = {};
            typeOptions['Fruit'] = [
              'Apple',
              'Pear',
              'Banana',
              'Plum',
              'Peach'
            ];
            typeOptions['Vegetable'] = [
              'Broccoli',
              'Carrot',
              'Pumpkin'
            ];

            function newchangeCategory() {
              var categoryChoice = document.getElementById('newcategory');
              var typeChoice = document.getElementById('newtype');
              var selectedCategoryChoice = categoryChoice.options[categoryChoice.selectedIndex].value; //line 340
              console.log(selectedCategoryChoice);
              while (typeChoice.options.length) {
                typeChoice.remove(0);
              }
              var typesAvailable = typeOptions[selectedCategoryChoice];
              if (typesAvailable) {
                var i;
                for (i = 0; i < typesAvailable.length; i++) {
                  var type = new Option(typesAvailable[i], typesAvailable[i]);
                  typeChoice.options.add(type);
                }
              }
            };
          </script>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close
                    </button>
        <button id="newsavebutton" type="button" class="btn btn-primary" data-dismiss="modal">Save changes
                    </button>
      </div>
    </div>
  </div>
</div>

采纳答案by Lalit Sachdeva

The reason why it was not working is that of one small spelling mistake, please have a look at the category id given in HTML and used by you in the script

它不工作的原因是一个小的拼写错误,请查看 HTML 中给出的类别 id 并在脚本中使用

var categoryChoice = document.getElementById('newCategory');

Please use newCategory with capital "C".

请使用带有大写“C”的 newCategory。

回答by Springer F

Probleme in capitalized character , change newcategoryby newCategoryin the js code : so the line would be var categoryChoice = document.getElementById('newCategory');

Probleme在大写字符,改变newcategorynewCategory在JS代码:太行会 var categoryChoice = document.getElementById('newCategory');

working snippet :

工作片段:

var typeOptions = {};
typeOptions['Fruit'] = [
  'Apple',
  'Pear',
  'Banana',
  'Plum',
  'Peach'
];
typeOptions['Vegetable'] = [
  'Broccoli',
  'Carrot',
  'Pumpkin'
];

function newchangeCategory() {
  //here you make the change newCategory iinstead of newcategory
  var categoryChoice = document.getElementById('newCategory');
  var typeChoice = document.getElementById('newtype');
  var selectedCategoryChoice = categoryChoice.options[categoryChoice.selectedIndex].value; //line 340
  console.log(selectedCategoryChoice);
  while (typeChoice.options.length) {
    typeChoice.remove(0);
  }
  var typesAvailable = typeOptions[selectedCategoryChoice];
  if (typesAvailable) {
    var i;
    for (i = 0; i < typesAvailable.length; i++) {
      var type = new Option(typesAvailable[i], typesAvailable[i]);
      typeChoice.options.add(type);
    }
  }
};
<div class="modal fade" id="newfoodModal" tabindex="-1" role="dialog" aria-labelledby="newfoodLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">

                 <span aria-hidden="true">&times;</span>
                </button>
        <h3 class="modal-title" id="newfoodLabel">New Food</h3>
        <br>
        <div>
          <div class="col-sm-12">
            <label for="category" id="newCategoryLabel" style="text-align: left">Category</label>
            <select name="category" id="newCategory" onchange="newchangeCategory()" class="form-control"> //line 273
                            <option value="" disabled selected hidden>Select a category</option>
                            <option value="Fruit">Fruit</option>
                            <option value="Vegetable">Vegetable</option>
                        </select>
          </div>
          <div class="col-sm-12">
            <label for="type" id="newtypeLabel" style="text-align: left">Type</label>
            <select name="type" id="newtype" class="form-control"></select>
          </div>

        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close
                </button>
        <button id="newsavebutton" type="button" class="btn btn-primary" data-dismiss="modal">Save changes
                </button>
      </div>
    </div>
  </div>
</div>