2013-02-15 78 views
6

我有一個表單可以出現在不同的頁面上,並且根據情況,字段並不總是必需的。點擊後,隱藏div並刪除所需的屬性

我有隱藏div的代碼,但需要不再需要輸入字段。使用HTML5必需屬性。無法使代碼正常工作。代碼如下:

$('#detailssame').click(function() { 
    if($(this).is(':checked')) { 
     $(\"#detailssamehide\").hide(); 
    } else { 
     $(\"#detailssamehide\").show(); 
    }    
}); 
$('.fullboxform input[type=text], .fullboxform select').each(function() { 
      $(this).removeAttr('required'); 
}); 

非常感謝所有幫助。

原來上面的代碼不會正常工作,但使用道具

回答

6

嘗試使用prop()功能設置HTML5特性提供備選答案。

$(function() { 
    $('#detailssame').click(function() { 
     var checked = $(this).is(':checked'); 
     if(checked) { 
      $("#detailssamehide").hide(); 
     } else { 
      $("#detailssamehide").show(); 
     }  
     $('.fullboxform input[type=text], .fullboxform select').each(function() { 
      $(this).prop('required', !checked); 
     }); 
    }); 
}); 

http://jsfiddle.net/ThsXU/

+0

根據我的閱讀,設置prop('required',false)''不能可靠地移除所有瀏覽器中的所需狀態。你必須使用removeAttr('required')''在所有瀏覽器中獲得穩定的結果。 – Jpsy 2016-02-07 13:47:01

1

刪除反斜槓,就足以讓我跑與預期效果的代碼。

+0

斜槓在那裏,因爲它是由PHP輸出的。你運行正確無誤。只是進一步與控制檯進行了檢查,並沒有意識到我有一些需要的輸入不是文本。 – 2013-02-15 02:41:23

+0

儘量不要在PHP中輸出js,因爲它可以防止緩存,並且更容易混淆和難以維護。最重要的是,避免將一種語言的代碼放入另一種語言的字符串中。 – 2013-02-15 02:48:24