隐藏div

时间:2016-07-06 20:00:22

标签: javascript jquery

我有这样的联系表格

<form action="" method="POST">
<div>
  <fieldset>
    <p dir="rtl">
      <label>case1</label>
      <select id="Color" required="required">
        <option value="">please select</option>
        <option value="redd">sell</option>
        <option value="greenn">rent</option>
      </select>
    </p>
  </fieldset>
</div>
<div class="redd box">
   <input dir="rtl" type="text" name="pricerange" required />
     <input dir="rtl" type="text" name="room" />
</div>
<div class="greenn box">
   <input dir="rtl" type="text" name="rentrange" required />
  <input dir="rtl" type="text" name="morgage" />
</div>
<p dir="rtl"><input name="submit" type="submit" value="submit" /></p>
</form>

如您所见,我根据用户从表单开头的下拉列表中选择的值显示或隐藏两个div框“redd box”和“greenn box”。如你所见,我在这个div框中需要输入和可选输入。但是当我选择其中一个div时,我必须填写必填字段和可选字段,否则我无法提交表单。有什么想法吗?谢谢

$(document).ready(function(){
    $("#Color").change(function () {
        $(this).find("option:selected").each(function(){
            if($(this).attr("value")=="redd"){
                $(".box").not(".redd").hide().find("input").prop("required", false);
                $(".redd").show().find("input").prop("required", true);
            }
            else if($(this).attr("value")=="greenn"){
                $(".box").not(".greenn").hide().find("input").prop("required", false);
                $(".greenn").show().find("input").prop("required", true);
            }
            else{
                $(".box").hide();
            }
        });
    }).change();
});

4 个答案:

答案 0 :(得分:1)

使用.removeAttr('required')代替.prop('required', false)

答案 1 :(得分:1)

最后,我得到了答案,感谢所有向我发送评论和答案的朋友 javascript必须改变如下:

<select id="funsports" name="funsports">
   <option value="">sports</option>
   <option value="football">grapes</option>
   <option value="tennis">mango</option>
</select>
另外如果我们在div中有一个select选项,则上面的javascrpt必须改变,如下所示

$(document).ready(function(){
    $("#Color").change(function () {
        $(this).find("option:selected").each(function(){
            if($(this).attr("value")=="redd"){
                $(".box").not(".redd").hide().find('input').removeAttr('required');
                $(".redd").show();
            }
            else if($(this).attr("value")=="greenn"){
                $(".box").not(".greenn").hide().find('input').removeAttr('required');
                $(".greenn").show();
            }
            else{
                $(".box").hide();
            }
        });
    }).change();
});

答案 2 :(得分:0)

在所有浏览器中都不能接受将required设置为false(例如,Internet Explorer 8不支持它)。您需要删除该属性。

 $(".box").not(".redd").hide().find("input").removeAttr('required');

 $(".box").not(".greenn").hide().find("input").removeAttr('required');

有关详细信息,请参阅this链接

答案 3 :(得分:0)

<强>被修改

您可以使用xAxis: { xAxis: { type: 'datetime', }, id: i, title: { text: tag.name, style: { color: color } }, ineWidth: 1, lineColor: color }

试试这个:

.removeAttr('required')