我正在处理我的 Django
项目,我遇到了 Javascript
部分和 IE 11
的问题。
我的函数适用于 Firefox
和 Chrome
,但不适用于 Internet Explorer 11。
过程:
我有一个带有复选框、下拉列表和提交按钮的表格。 当我没有选中任何复选框和在下拉列表中选择任何值时,此按钮被禁用。
图片:
如您所见,提交按钮在以下情况下被禁用:
- 未选中复选框和列表值
- 选中复选框但未列出值
- 未选中复选框但已选中列表值
提交按钮仅在复选框和列表值被选中时启用。
我的代码:
Javascript 部分:
<script type="application/javascript">
function checkValid() {
var cbChecked = $(".fake-radio").is(":checked"); // check if checked
var selectelem = document.getElementById('manage-doc-year');
var btnelem = document.getElementById('document-button');
btnelem.disabled = !selectelem.value;
var dropdown_value = btnelem.disabled;
$("#document-button").prop("disabled", !cbChecked || dropdown_value);
}
$(function () {
checkValid(); // run it for the first time
$(".fake-radio").on("change", checkValid); // bind checkbox
$("#manage-doc-year").on("input", checkValid) // bind textbox
});
</script>
HTML 部分:
<div class="col-md-offset-1 col-md-5">
<h4> {% trans "List of documents:" %} </h4>
<form action="" method="POST">
{% csrf_token %}
<table id="document-table" class="table table-bordered table-striped table-condensed table_model">
<thead>
<tr>
<th>{% trans 'Choice' %}</th>
<th>{% trans 'Document title' %}</th>
</tr>
</thead>
<tbody>
{% for document in query_document %}
<tr>
<td><input type="checkbox" class="fake-radio" id="document-checkbox" name="DocumentChoice"
value="{{ document.id }}"></td>
<td>{{ document.title }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<select id="manage-doc-year" name="q1year" value="{{ request.get.q1year }}" required>
<option selected="selected">
<option value="" selected disabled hidden></option>
</option>
</select>
<button class="btn btn-default" id="document-button" type="submit"
name="UpdateDocument">{% trans "Submit" %}</button>
</form>
</div>
IE 11:
对于 IE 11,只有当我先选择下拉值,然后选中复选框时,它才会起作用。但如果我先登记,然后选择值(value),就不会了。为什么?
谢谢!
最佳答案
IE 没有 support input
事件 <select>
元素。
考虑收听change
IE 上的事件。
你可以这样写:
$("#manage-doc-year").on("change", checkValid)
代替:
$("#manage-doc-year").on("input", checkValid)
注:虽然change
所有浏览器都支持事件,它的行为与 input
有点不同事件的(source):
change
fires less often thaninput
– it only fires when the changes are committed by the user.
并且可能因不同的浏览器而异 ( source ):
Different browsers do not always agree whether a
change
event should be fired for certain types of interaction. For example, keyboard navigation in<select>
elements never fires a change event in Gecko until the user hits Enter or switches the focus away from the<select>
关于Javascript <input> 不适用于 IE 11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53041498/