小白前端入門筆記(20),表單設(shè)置必填項
點擊上方藍字,關(guān)注并星標,和我一起學技術(shù)。
大家好,歡迎來到freecodecamp HTML專題第20篇。
今天的挑戰(zhàn)關(guān)于表單提交的必填項。
背景知識
我們在網(wǎng)站上注冊用戶或者是進行其他操作的時候,經(jīng)常會遇到瀏覽器提示我們某某選項是必填的,如果不填不可以進行提交。有沒有想過這是如何實現(xiàn)的呢?
其實這個功能并不復雜,只需要我們在表單當中將對應的選項添加一個required屬性即可。required是英文需要的意思,它不需要任何賦值。
舉個例子:
<input type="text" required>
題意
將文本的input標簽添加required屬性,這樣的話我們在提交表單的時候必須要填寫相應的項。
接著嘗試在不輸入任何文本的情況下提交,看看瀏覽器會給出怎樣的反饋?
要求
你的文本 input標簽需要添加required屬性
編輯器
<h2>CatPhotoApp</h2>
<main>
<p>Click here to view more <a href="#">cat photos</a>.</p>
<a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a>
<p>Things cats love:</p>
<ul>
<li>cat nip</li>
<li>laser pointers</li>
<li>lasagna</li>
</ul>
<p>Top 3 things cats hate:</p>
<ol>
<li>flea treatment</li>
<li>thunder</li>
<li>other cats</li>
</ol>
<form action="https://freecatphotoapp.com/submit-cat-photo">
<input type="text" placeholder="cat photo URL">
<button type="submit">Submit</button>
</form>
</main>
解法
遵循題目要求修改設(shè)置即可。
<h2>CatPhotoApp</h2>
<main>
<p>Click here to view more <a href="#">cat photos</a>.</p>
<a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a>
<p>Things cats love:</p>
<ul>
<li>cat nip</li>
<li>laser pointers</li>
<li>lasagna</li>
</ul>
<p>Top 3 things cats hate:</p>
<ol>
<li>flea treatment</li>
<li>thunder</li>
<li>other cats</li>
</ol>
<form action="https://freecatphotoapp.com/submit-cat-photo">
<input type="text" placeholder="cat photo URL" required>
<button type="submit">Submit</button>
</form>
</main>
加入required屬性之后,如果我們不填寫任何內(nèi)容進行提交,瀏覽器會做出如下提示:

想要親自動手嘗試一下的同學不要忘了點擊文末的閱讀原文進行跳轉(zhuǎn)哦~
文章就到這里,給個三連再走吧~
評論
圖片
表情
