我想做一个条件,如果txtDate == txtDateEND
和表单selJam
将显示为dropdown
。如果 txtDate 不等于 txtDateEnd 和selJam
的表单将被隐藏或不再显示。 根据我的代码,我仍然无法使 selJam 显示或隐藏。
function checkDates() {
var txtDate = $('#txtDate');
var txtDateEnd = $('#txtDateEnd');
var selJam = $('selJam');
if (txtDate.val() == txtDateEnd.val()) {
selJam.show();
} else {
selJam.hide();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div>
Date Start<input type="date" name="txtDate" id="txtDate" onchange="checkDates()" /> Date End<input type="date" name="txtDateEnd" id="txtDateEnd" onchange="checkDates()" />
</div>
</div>
<select id="selJam" name="selJam">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
</div>
- 您在选择器上缺少 #
- 试试这个 - 更优雅,推荐不引人注目。注意我如何删除 onchange 并将事件处理程序分配给字段
$(function() {
$('[type=date]').on("change",function() {
var txtDate = $('#txtDate');
var txtDateEnd = $('#txtDateEnd');
$("#selJam").toggle(txtDate.val() === txtDateEnd.val())
}).change(); // initialise on load or use CSS to hide
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div>
Date Start<input type="date" name="txtDate" id="txtDate"/> Date End<input type="date" name="txtDateEnd" id="txtDateEnd" />
</div>
<div>
<select id="selJam" name="selJam">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
</div>
您很接近,您只需将#
添加到您的选择器中,如下所示$('#selJam')
:
var selJam = $('#selJam');
但我建议避免使用内联事件onchange
并将change
事件附加到您的 JS 部分中,例如:
注意:默认情况下,您的逻辑最好隐藏selJam
元素。
$('#txtDate, #txtDateEnd').change(function() {
var txtDate = $('#txtDate').val();
var txtDateEnd = $('#txtDateEnd').val();
var selJam = $('#selJam');
if (txtDate == txtDateEnd) {
selJam.show();
} else {
selJam.hide();
}
//OR
//selJam.toggle(txtDate == txtDateEnd)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
Date Start<input type="date" name="txtDate" id="txtDate" />
Date End<input type="date" name="txtDateEnd" id="txtDateEnd" />
</div>
<select id="selJam" name="selJam" style="display: none">
<option>1</option>
<option>2</option>
<option>3</option>
</select>