![](/img/trans.png)
[英]Add '*' to the label of input fields with the 'required' attribute with CSS
[英]Hide label for input without attribute “required” (float label)
我有以下代碼:
<span class="field">
<input type="text" id="first-name" placeholder="First Name" required />
<label for="first-name">First Name</label>
</span>
<span class="field">
<input type="text" id="last-name" placeholder="Last Name" />
<label for="last-name">Last Name</label>
</span>
第二個輸入的標簽(“姓氏”)從一開始就可見,不僅像“名字”標簽一樣聚焦。 兩個輸入之間的區別僅在於屬性“必需”,對於“姓氏”字段我不需要。
如何在不隱藏“必需”屬性的情況下為輸入添加標簽? 我需要僅將其顯示為具有過渡效果的焦點。 類似於“名字”字段的工作。
您可以使用相鄰的兄弟選擇器。 將以下代碼添加到您的CSS文件中。
input[required] + label {
display: none;
}
還要對姓氏字段使用必填項,但是在提交表單時覆蓋javascript輸入的姓氏的必填屬性。
document.getElementById("last-name").required = false;
我知道這個問題是9個月前提出的,但是將來可以對某人有所幫助。 我猜您不能提交表單,因為所有帶有float標簽的字段都應具有必填屬性。如果您將字段保留為空,則表單不會提交。 如果刪除該屬性,則標簽可見,可以提交表單,但是浮動標簽的想法被破壞了。
如果我是正確的,請嘗試以下代碼:
$( document ).ready(function() {
$('#sub-btn').click(function validateForm() {
var isValid = true;
$('.field').each(function() {
if ( $(this).val() === '' )
$(this).removeAttr("required");
});
return isValid;
});
});
這個對我有用。 您應該將提交按鈕設置為 id =“ sub-btn”,以便在單擊該按鈕時將清除必需的屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.