小白前端入门笔记(20),表单设置必填项
点击上方蓝字,关注并星标,和我一起学技术。
大家好,欢迎来到freecodecamp HTML专题第20篇。
今天的挑战关于表单提交的必填项。
背景知识
我们在网站上注册用户或者是进行其他操作的时候,经常会遇到浏览器提示我们某某选项是必填的,如果不填不可以进行提交。有没有想过这是如何实现的呢?
其实这个功能并不复杂,只需要我们在表单当中将对应的选项添加一个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>
解法
遵循题目要求修改设置即可。
<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属性之后,如果我们不填写任何内容进行提交,浏览器会做出如下提示:

想要亲自动手尝试一下的同学不要忘了点击文末的阅读原文进行跳转哦~
文章就到这里,给个三连再走吧~
评论
