jquery - 加载预选选项时隐藏和显示表单元素
问题描述
我有这个 jQuery 来显示和隐藏表单字段。我首先隐藏它们
$('#edit-profile-letter-of-introduction-field-sign-off').hide();
$('#edit-profile-letter-of-introduction-field-signatory').hide();
$('#edit-profile-letter-of-introduction-field-position').hide();
然后我有一个更改事件,根据选择字段的值显示和隐藏它们
$('#edit-profile-letter-of-introduction-field-template-und').change(function() {
switch ($(this).val()) {
case '1':
$('#edit-profile-letter-of-introduction-field-sign-off').show();
$('#edit-profile-letter-of-introduction-field-signatory').hide();
$('#edit-profile-letter-of-introduction-field-position').hide();
break;
etc etc
工作正常。然后我保存表格。当表单返回时,所有字段都再次隐藏。
我想发生的是加载表单时,并且在选择字段中已经有一个选择 - 或当Select字段具有默认值时 - 然后我希望隐藏或显示其他表单字段,而无需更改事件。
然后,如果用户更改选择字段的值,我希望更改事件起作用。
解决方案
请参考下面的代码示例。在下面的示例中,我正在使用默认值“test”加载输入,因此第一个案例将在加载时执行。然后,如果您将输入更改为“test1”,那么它将执行第二种情况。同样,您可以添加更多案例。
<input type="text" id="demoInput" value="test">
<lable id="lbl">test</lable>
<lable id="lbl1">test1</lable>
<lable id="lbl2">test2</lable>
$(document).ready(function(){
var defaultValue = $("#demoInput").val();
hideShowElements(defaultValue);
$("#demoInput").change(function(){
hideShowElements($(this).val());
});
});
function hideShowElements(defaultValue){
switch (defaultValue) {
case 'test':
$("#lbl").show();
$("#lbl1").hide();
$("#lbl2").hide();
break;
case "test1":
$("#lbl").hide()
$("#lbl1").show();
$("#lbl2").show();
break;
};
}
推荐阅读
- c++ - 如何使用地图容器?
- react-native - 无法识别的字体系列“entypo”
- corda - 在corda的H2控制台中找不到空指针异常和表“SYNONYMS”错误
- java - 如何从Java中非常长的文本文件中删除以特定字符开头和结尾的行?
- sql - 如何在 SQL Server 的非标识列中查找间隙序列
- c# - Xamarin 表单蓝牙键盘输入输入缓慢
- ios - 即使在调用委托方法后,collectionview 单元格也不可见
- android - DividerItemDecoration 可绘制完全不透明
- reactjs - react-native 项目中的 .flowconfig 文件丢失
- javascript - 如何编写此正则表达式以仅替换 url