๋ฐ˜์‘ํ˜•

form ์™ธ๋ถ€์—์„œ form ๊ด€๋ จ ์š”์†Œ ์—ฐ๊ฒฐ


form ๊ด€๋ จ ์š”์†Œ(button, input ๋“ฑ)์˜ form ์†์„ฑ์œผ๋กœ ์–ด๋–ค form์— ์†ํ• ์ง€(์—ฐ๊ฒฐ) ์ง€์ • ํ•  ์ˆ˜ ์žˆ๋‹ค. ์ฃผ๋กœ form ์™ธ๋ถ€์— ์žˆ๋Š” form ๊ด€๋ จ ์š”์†Œ๋ฅผ form์— ์—ฐ๊ฒฐํ•  ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค. ์ด๋•Œ form ์š”์†Œ์˜ id ๊ฐ’๊ณผ form ๊ด€๋ จ ์š”์†Œ์˜ form ์†์„ฑ ๊ฐ’์ด ๋™์ผํ•ด์•ผ ํ•˜๊ณ , ๊ฐ™์€ ๋ฌธ์„œ(document)์— ์žˆ์–ด์•ผ ๋œ๋‹ค.

 

form ๋‚ด๋ถ€์— ์žˆ๋Š” form ๊ด€๋ จ ์š”์†Œ๋Š” ์ž๋™์œผ๋กœ ํ•ด๋‹น form์— ์†ํ•˜๋ฏ€๋กœ form ์†์„ฑ์œผ๋กœ ๋ช…์‹œํ•˜์ง€ ์•Š์•„๋„ ๋œ๋‹ค.

<form id="register">
  <input type="email" name="email" />
  <input type="password" name="password" />
</form>

<!-- form ์™ธ๋ถ€์— ์žˆ์ง€๋งŒ form ์†์„ฑ์œผ๋กœ register ์•„์ด๋””๋ฅผ ๊ฐ€์ง„ form์— ์—ฐ๊ฒฐํ–ˆ๋‹ค -->
<button type="submit" form="register">Submit</button>

 

๐Ÿ’ก button ์š”์†Œ์˜ type ์†์„ฑ ๊ธฐ๋ณธ ๊ฐ’์€ submit์ด๋ฉฐ, ํด๋ฆญํ•ด์„œ ์–‘์‹์„ ์ œ์ถœํ•˜๋ฉด ์ƒˆ๋กœ๊ณ ์นจํ•˜๋Š” ๊ธฐ๋ณธ ๋™์ž‘์„ ๊ฐ€์ง„๋‹ค. ์ƒˆ๋กœ๊ณ ์นจ์„ ๋ฐฉ์ง€ํ•˜๋ ค๋ฉด form ์š”์†Œ onsubmit ํ•ธ๋“ค๋Ÿฌ์— event.preventDefault() ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค.

 

์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ๋กœ form ์ ‘๊ทผํ•˜๊ธฐ


์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์—์„  document ๊ฐ์ฒด๋ฅผ ํ†ตํ•ด form์— ์ง์ ‘ ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋‹ค. form์ด๋‚˜ form ๊ด€๋ จ ์š”์†Œ์— ๋ช…์‹œํ•œ name ํ˜น์€ id ์†์„ฑ์œผ๋กœ ์›ํ•˜๋Š” form ์š”์†Œ๋ฅผ ์„ ํƒํ•  ์ˆ˜ ์žˆ๋‹ค.

// ๋ฌธ์„œ์˜ ์ฒซ๋ฒˆ์งธ form
const firstForm = document.forms[0]; 
// <form id="register">...
const registerForm = document.forms.register; 

// <input type="email" name="email">
const emailField1 = registerForm.elements.email; 
// ์งง์€ ํ‘œ๊ธฐ๋ฒ• <input type="email" name="email">
const emailField2 = registerForm.email; 
// true
console.log(emailField1 === emailField2);

 

๋˜ํ•œ ๋ชจ๋“  form ๊ด€๋ จ ์š”์†Œ๋Š” form ์†์„ฑ์œผ๋กœ ์ž์‹ ์ด ์†ํ•ด์žˆ๋Š” form์„ ์ฐธ์กฐํ•  ์ˆ˜ ์žˆ๋‹ค.

console.log(emailField1.form); // <form id="register">...

 

 

๋ ˆํผ๋Ÿฐ์Šค


 


๊ธ€ ์ˆ˜์ •์‚ฌํ•ญ์€ ๋…ธ์…˜ ํŽ˜์ด์ง€์— ๊ฐ€์žฅ ๋น ๋ฅด๊ฒŒ ๋ฐ˜์˜๋ฉ๋‹ˆ๋‹ค. ๋งํฌ๋ฅผ ์ฐธ๊ณ ํ•ด ์ฃผ์„ธ์š”
๋ฐ˜์‘ํ˜•