简体   繁体   English

上的jQuery类型错误无法读取未定义的属性“长度”

[英]Jquery type error on cannot read property 'length' of undefined

I am working on to change drop down menu on selection. 我正在努力更改选择的下拉菜单。 For that I am using jquery, ajax with json. 为此,我使用带有json的jquery,ajax。

function ChooseGroupScript() {

                    $.getJSON('edit_scripts.php', {group:$('#group').val()}, function(data) {
                        var select = $('#subject');
                        var options = select.attr('options');
                        $('option', select).remove();

                            $.each(data, function(index, array) {
                                options[options.length] = new Option(array['subject']);
                            });

                    });

                }

                $(document).ready(function() {
                        ChooseGroupScript();
                        $('#group').change(function() {
                                ChooseGroupScript();
                        });

                });

I checked in console: i am getting error like this: 我在控制台中检查了以下错误:

Jquery type error on cannot read property 'length' of undefined

this is my PHP: 这是我的PHP:

if(isset($_GET['group'])){
$currentscript = $clients->curr_group_content($_GET['group']);
$scriptscount = sizeof($currentscript);
      for($i=0;$i<$scriptscount;$i++){
        $subject = $currentscript[$i]['subject'];
      }
}
echo json_encode($subject);

HTML: HTML:

<form>

<select name="group" id="group">
    <option>comming from database.....</option>
</select>

<select name="subject" id="subject">
</select>
</form>

options is not an attribute on the select element. options不是select元素上的属性。 You are probably just looking to add the new Options to the element directly: 您可能只是想将新的Options直接添加到元素:

       var select = $('#subject');
       // remove this: var options = select.attr('options');
       $('option', select).remove(); // or select.empty() to clean it out

       $.each(data, function(index, array) {
            select.append(new Option(array['subject']));
       });

In your code you have 在您的代码中

var options = select.attr('options');

it's not right, because it is not an attribute. 这是不对的,因为它不是属性。 Right way to get all options 获得所有选择的正确方法

var options = $('#subject options');

And in your loop you can 在您的loop您可以

var select = $('#subject').empty();
$.each(data, function(index, val) {
    select.append($('<option/>', { 'value':index, 'text':val }));
});

A similar answer with example is here. 示例的类似答案在这里。

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

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