【问题标题】:Hide and show form elements when preselected option is loaded加载预选选项时隐藏和显示表单元素
【发布时间】:2020-02-03 18:30:16
【问题描述】:

我有这个 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字段中已经有一个选择 - 或者选择字段有默认值 - 然后我希望隐藏或显示的其他表单字段但不需要更改事件。

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

【问题讨论】:

    标签: jquery hide show


    【解决方案1】:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-24
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-23
    相关资源
    最近更新 更多