inputの概要
| ユーザーが入力するフォームフィールドを作成 HTMLタグ | ||
|
<input type=”種類” name=”名前”> 概要 inputタグは、ユーザーがデータを入力するためのフィールドを作成するためのHTMLタグです。テキスト入力、パスワード入力、チェックボックス、ラジオボタン、ファイルアップロードなど、さまざまな種類があります。 |
||
|
inputタグの主な属性
| 属性 | 説明 | 使用例 |
|---|---|---|
type |
入力フィールドの種類を指定 | <input type="text"> |
name |
フォーム送信時のデータ識別名 | <input type="text" name="username"> |
value |
初期値を指定 | <input type="text" value="初期値"> |
placeholder |
入力例を示すプレースホルダー | <input type="text" placeholder="名前を入力"> |
required |
入力必須にする | <input type="text" required> |
disabled |
入力不可にする | <input type="text" disabled> |
readonly |
編集不可(送信は可能) | <input type="text" readonly> |
maxlength |
最大文字数を指定 | <input type="text" maxlength="20"> |
pattern |
正規表現で入力を制限 | <input type="text" pattern="[A-Za-z0-9]+"> |
inputタグの基本的な使い方
以下の例では、ユーザーが名前を入力できるテキストフィールドを作成しています。
<form>
<label for="name">名前:</label>
<input type="text" id="name" name="name" placeholder="あなたの名前">
<button type="submit">送信</button>
</form>
実行例:
さまざまな入力フィールドの実行例
以下の例では、inputタグのtype属性を変更し、さまざまな入力フィールドを作成します。
<form>
<p>メールアドレス: <input type="email" name="email" required></p>
<p>パスワード: <input type="password" name="password"></p>
<p>誕生日: <input type="date" name="birthdate"></p>
<p>数量: <input type="number" name="quantity" min="1" max="10"></p>
<p>同意する: <input type="checkbox" name="agree"></p>
<p>性別:
<input type="radio" name="gender" value="male"> 男性
<input type="radio" name="gender" value="female"> 女性
</p>
<p>ファイルをアップロード: <input type="file" name="upload"></p>
<button type="submit">送信</button>
</form>
実行例:
数値入力の制限
以下の例では、最小値と最大値を指定した数値入力フィールドを作成します。
<input type="number" name="age" min="18" max="99">
実行例:
カラー選択
カラー選択用の入力フィールドを作成できます。
<input type="color" name="favcolor">
実行例:
注意事項
- 適切な
type属性を選択し、適切な入力を促す。 required属性を使用して必須入力を設定する。- ユーザー体験を向上させるために
placeholderを活用する。 - メールアドレスやパスワードの入力には適切な
typeを選択する(例:type="email")。 - セキュリティのために、パスワードフィールドには
type="password"を使用する。
よくある質問
- Q: inputタグに閉じタグは必要ですか?
- A: いいえ、inputタグは空要素なので閉じタグ(
</input>)は不要です。 - Q: 文字数を制限するには?
- A:
maxlength属性を使用すると、入力可能な最大文字数を制限できます。 - Q: ラジオボタンのうち1つだけを選択させるには?
- A: 同じ
name属性を持たせると、1つの選択肢のみが選択可能になります。 - Q: 画像をアップロードするには?
- A:
type="file"を指定し、フォームにenctype="multipart/form-data"を設定します。
まとめ
inputタグは、ユーザーがデータを入力するためのフィールドを作成する。type属性で異なる入力形式を指定できる。- フォーム送信には
name属性を設定する。 - セキュリティのため、適切な入力制限(
pattern,maxlength)を設ける。 - CSSを使ってデザインやレイアウトを調整できる。