Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

JavaScript에서 페이지를 다시 로드하기 위한 양식 작성 중지

<시간/>

우리가 달성해야 하는 것은 사용자가 이 HTML 양식을 제출할 때 클라이언트 측에서 제출 이벤트를 처리하고 양식이 제출되자마자 브라우저가 다시 로드되는 것을 방지하는 것이라고 가정해 보겠습니다.

HTML 양식

<form name="formcontact1" action="#">
<input
type='text'
name='email'
size="36"
placeholder="Your e-mail :)"/>
<input
   type="submit"
   name="submit"
   value="SUBMIT"
   onclick="ValidateEmail(document.formcontact1.email)"
/>
</form>

이제 가장 쉽고 신뢰할 수 있는 방법은 ValidateEmail() 함수를 수정하여 정의 상단에 다음 줄을 포함시키는 것입니다. −

function ValidateEmail(event, inputText){
   event.preventDefault();
   //remaining function logic goes here
}

preventDefault()가 하는 일은 브라우저에 기본 동작을 방지하고 클라이언트 측 자체에서 양식 제출 이벤트를 처리하도록 하는 것입니다.

이에 대한 전체 HTML 코드는 -

예시

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form name="formcontact1" action="#">
<input
type='text'
name='email'
size="36"
placeholder="Your e-mail :)"/>
<input
   type="submit"
   name="submit"
   value="SUBMIT"
   onclick="ValidateEmail(document.formcontact1.email)"
/>
</form>
<script>
{
   function ValidateEmail(event, inputText){
      event.preventDefault();
      //remaining function logic goes here
   }
}
</script>
</body>
</html>