问题
I am trying to insert an HTML using my controller to a div, but I do not know what is wrong with my JS code, it always return Uncaught TypeError: Cannot set property 'innerHTML' of null. Is there anything I missed?
My Controller:
$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;
My View
<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>
My 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>';
});
};
回答1:
remove the hash #
.use #
when you use jquery to select element by id.
document.getElementById('htmlcontainer')
if you are using jquery then you should use # ( for id)
$('#htmlcontainer').html('text');
edit
another problem
you have added div tags inside select tag directly.select tag cannot have div tags directly only <option>
or <optgroup>
elements are allowed.so you have to change it.
read more
回答2:
Go ahead and remove the hash symbol #
, so it looks like this:
document.getElementById('htmlcontainer').innerHTML = '<h1>Something</h1>';
If you think about it, what you're trying to do is to fetch an element with an ID of #htmlcontainer
, which doesn't exist.
In jQuery however, you use the #
symbol.
来源:https://stackoverflow.com/questions/38381181/cannot-insert-html-on-var-using-getelementbyid