首页 > 解决方案 > 加载预选选项时隐藏和显示表单元素

问题描述

我有这个 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字段具有默认值时 - 然后我希望隐藏或显示其他表单字段,而无需更改事件。

然后,如果用户更改选择字段的值,我希望更改事件起作用。

标签: jqueryhideshow

解决方案


请参考下面的代码示例。在下面的示例中,我正在使用默认值“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;
   };
 } 

推荐阅读