LoginSignup
0
0

More than 1 year has passed since last update.

Javascript フォームに入力した値をコンソールで取得できない

Last updated at Posted at 2022-12-07

環境

Mac(M1, 2020)
vscode5

[概要]

javascriptでTODOアプリを作成中、フォームに入力した値を取れているか確認するために
console.logで確認してみると
一瞬だけ入力した値がコンソールに表示され取得できてない現状

const form = document.getElementById("form");
const input = document.getElementById("input");

form.addEventListener("submit", function () {
  
  console.log(input.value);
});

スクリーンショット 2022-12-07 18.11.16.png

原因としてはフォームでenterを押すと画面がリロードされるとのこと(元々そうなってる)
今はそれをされたくないのでリロードのイベントを無しにしたい
すでに使っているaddEventListenerを使うと関数の中の引数にeventとゆう種類のデータを取得できる
eventにはpreventDefaultメゾットがありこれを使うとデフォルトのイベントを発生しないようにできる
今回の場合は、formをsubmit(エンターキーを押す)したときのブラウザのリロードを中断できる

やったこと

1.関数の中の引数にevent
2.event.preventDefaultを追加

const form = document.getElementById("form");
const input = document.getElementById("input");

form.addEventListener("submit", function (event) {
  event.preventDefault();
  console.log(input.value);
});

結果

入力した値が取得できた
スクリーンショット 2022-12-07 18.28.38.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0