无法使用getElementById在var上插入HTML

时间:2016-07-14 18:03:02

标签: javascript jquery codeigniter

我正在尝试使用我的控制器将一个HTML插入到div中,但我不知道我的JS代码有什么问题,它总是返回Uncaught TypeError:无法设置null的属性'innerHTML'。我错过了什么吗?

我的控制器:

$this->load->model('model_admin','modeladmin');

$branchid = $this->input->post('subject_branchid');

$classdata = $this->modeladmin->getclassesviabranch('169APC00002');

$selectoption = "";

foreach ($classdata as $classitems)
{

    $selectoption .= "<option value='".$classitems['class_id']."'>".$classitems['class_name']."</option>";
}

echo $ selectoption;

我的观点

<select class="form-control" id="subject_branchid" name="subject_branchid" style="width:50%;" onchange="getvalues()">

    <?php

        foreach ($branches as $branch)
        {
            echo "<option value='".$branch['branch_id']."'>".$branch['branch_prefix']."</option>";
        }

    ?>

</select>

<br>
<input type="text" id="price" name="price" />
<br>


<select class="form-control" id="subject_classid" name="subject_classid" style="width:50%;">

    <div id="htmlcontainer" name="htmlcontainer"></div>

</select>

我的JS

<script>
function getvalues() 
{
    //get the value of the select when it changes
    var value = $("#subject_branchid").val()

    //make an ajax request posting it to your controller
    $.post('<?=site_url("admin/test")?>', {data:value},function(result) 
    {
    //change the input price with the returned value
    //$('#price').val(result);
    document.getElementById('#htmlcontainer').innerHTML = '<h1>Something</h1>';
    });
};

2 个答案:

答案 0 :(得分:1)

删除哈希#。当您使用jquery按ID选择元素时,请使用#

 document.getElementById('htmlcontainer')

如果你使用的是jquery,那么你应该使用#(用于id)

$('#htmlcontainer').html('text');

修改

另一个问题

您已直接在select标签内添加了div标签。选择标签不能直接使用div标签只允许使用<option><optgroup>元素。因此您必须更改它。

read more

答案 1 :(得分:0)

继续删除哈希符号#,如下所示:

document.getElementById('htmlcontainer').innerHTML = '<h1>Something</h1>';

如果您考虑一下,那么您尝试做的就是获取ID为#htmlcontainer的元素,该元素不存在。

但是,在jQuery中,您使用#符号。