jquery hidden div删除字段必需

时间:2018-03-13 13:44:26

标签: javascript jquery django django-forms

如何删除隐藏字段中所需的内容。它必须在可见字段中保持必需。当选择其中一个选项时,需要删除所需的字段。这个表单创建了django框架。

例如,当选择“tuzel”时,需要从adi字段中删除所需字段。

Jquery代码

<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $("select").change(function(){
        $(this).find("option:selected").each(function(){
            var optionValue = $(this).attr("value");
            if(optionValue){

                $(".col").not("." + optionValue).hide();
                $("." + optionValue).show();
            } else{
                $(".col").hide();

            }
        });
    }).change();
});
</script>

<select name="secenek" class="form-control select2" required id="id_secenek">
  <option value="" selected>---------</option>

  <option value="tuzel">Tüzel</option>

  <option value="gercek">Gerçek</option>
</select>

              <div class="tuzel col col-lg-6">
                <div  id="fnWrapper" class=" parsley-input">
                  <label class="form-control-label">Firma Ünvanı: <span class="tx-danger">*</span></label>
                    <input type="text" name="firma_adi" class="form-control" id="id_firma_adi" maxlength="256" required/>
                </div>
              </div><!-- col-4 -->
              <div class="gercek col col-lg-6">
                <div  id="fnWrapper" class=" parsley-input">
                  <label class="form-control-label">Adı: <span class="tx-danger">*</span></label>
                    <input type="text" name="adi" data-parsley-class-handler="#fnWrappe" class="form-control" required="True" id="id_adi" maxlength="128" required/>
                </div>
              </div><!-- col-4 -->

2 个答案:

答案 0 :(得分:3)

我已经使用您的代码创建了一个小提琴,您可以在文件中如何申请。

请参阅:fiddle example

你需要在JS中添加两行:

$(document).ready(function(){
    $("select").change(function(){
        $(this).find("option:selected").each(function(){
            var optionValue = $(this).attr("value");
            console.log(optionValue);
            if(optionValue){
                $(".col").not("." + optionValue).hide();
                $("." + optionValue).show();
                                $('input[type="text"]').removeAttr('required');
                                $("." + optionValue + " input").attr('required','true');
            } else{
                $(".col").hide();

            }
        });
    }).change();
});

答案 1 :(得分:1)

if(optionValue){
    $(".col").not("." + optionValue).hide();
    $(".col").not("." + optionValue).removeAttr('required');​​​​​
    $("." + optionValue).show();
    $("." + optionValue).attr('required', true);
}