programing

양식 제출을 중지하는 JavaScript 코드

bestcode 2022. 9. 21. 00:10
반응형

양식 제출을 중지하는 JavaScript 코드

폼 제출을 정지하는 한 가지 방법은 JavaScript 함수에서 false를 반환하는 것입니다.

[ Submit ]버튼을 클릭하면 검증기능이 호출됩니다.나는 형식상 타당성을 입증하는 사례를 가지고 있다.이 조건이 충족되면 returnToPreviousPage()라는 함수를 호출합니다.

function returnToPreviousPage() {
    window.history.back();
}

JavaScript와 Dojo Toolkit을 사용하고 있습니다.

이전 페이지로 돌아가지 않고 양식을 제출합니다.이 제출을 중지하고 이전 페이지로 돌아가려면 어떻게 해야 합니까?

함수의 반환 값을 사용하여 양식 제출을 방지할 수 있습니다.

<form name="myForm" onsubmit="return validateMyForm();"> 

기능하고 있습니다.

<script type="text/javascript">
function validateMyForm()
{
  if(check if your conditions are not satisfying)
  { 
    alert("validation failed false");
    returnToPreviousPage();
    return false;
  }

  alert("validations passed");
  return true;
}
</script>

Chrome 27.0.1453.116m의 경우 위 코드가 작동하지 않으면 이벤트 핸들러의 파라미터 returnValue 필드를 false로 설정하여 작동시키십시오.

정보를 공유해줘서 샘에게 고마워.

편집:

validateMyForm()이 false를 반환하는 경우의 회피책으로 Vikram에게 감사를 표합니다.

 <form onsubmit="event.preventDefault(); validateMyForm();">

여기서 validateMyForm()은 검증에 실패했을 때 false를 반환하는 함수입니다.네임 이벤트를 사용하는 것이 포인트입니다.예를 들어 prevent Default()에는 사용할 수 없습니다.

prevent default 사용

도조 툴킷

dojo.connect(form, "onsubmit", function(evt) {
    evt.preventDefault();
    window.history.back();
});

j쿼리

$('#form').submit(function (evt) {
    evt.preventDefault();
    window.history.back();
});

Vanilla JavaScript

if (element.addEventListener) {
    element.addEventListener("submit", function(evt) {
        evt.preventDefault();
        window.history.back();
    }, true);
}
else {
    element.attachEvent('onsubmit', function(evt){
        evt.preventDefault();
        window.history.back();
    });
}

다음은 현재 작동 중입니다(Chrome 및 Firefox에서 테스트됨).

<form onsubmit="event.preventDefault(); validateMyForm();">

여기서 validateMyForm()은 반환되는 함수입니다.false검증에 실패했을 경우.요점은 이 이름을 사용하는 것이다.event. 에는 사용할 수 없습니다. e.preventDefault().

@Vikram Pudi의 답변을 바탕으로 순수 Javascript에서도 이와 같이 할 수 있습니다.

<form onsubmit="submitForm(event)">
    <input type="text">
    <input type="submit">
</form>

<script type="text/javascript">

    function submitForm(event){
        event.preventDefault();


    }
</script>

심플한 것을 사용하다button[ Submit ]버튼 대신 [Submit 버튼을 클릭합니다.또한 폼 제출을 처리하기 위해 JavaScript 함수를 호출합니다.

<input type="button" name="submit" value="submit" onclick="submit_form();"/>

의 기능script태그:

function submit_form() {
    if (conditions) {
        document.forms['myform'].submit();
    }
    else {
        returnToPreviousPage();
    }
}

시험해 볼 수도 있습니다.window.history.forward(-1);

쉬운 일을 하기 위한 많은 어려운 방법:

<form name="foo" onsubmit="return false">

당신의 모든 답변이 도움이 되었습니다.

마지막으로, 이 조작은 유효했습니다.(체크박스를 1개 이상 선택하지 않으면 경고와 같은 페이지에 남습니다.)

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <form name="helloForm" action="HelloWorld" method="GET"  onsubmit="valthisform();">
            <br>
            <br><b> MY LIKES </b>
            <br>
            First Name: <input type="text" name="first_name" required>
            <br />
            Last Name: <input type="text" name="last_name"  required />
            <br>
            <input type="radio" name="modifyValues" value="uppercase" required="required">Convert to uppercase <br>
            <input type="radio" name="modifyValues" value="lowercase" required="required">Convert to lowercase <br>
            <input type="radio" name="modifyValues" value="asis"      required="required" checked="checked">Do not convert <br>
            <br>
            <input type="checkbox" name="c1" value="maths"     /> Maths
            <input type="checkbox" name="c1" value="physics"   /> Physics
            <input type="checkbox" name="c1" value="chemistry" /> Chemistry
            <br>

            <button onclick="submit">Submit</button>

            <!-- input type="submit" value="submit" / -->
            <script>
                <!---
                function valthisform() {
                    var checkboxs=document.getElementsByName("c1");
                    var okay=false;
                    for(var i=0,l=checkboxs.length;i<l;i++) {
                        if(checkboxs[i].checked) {
                            okay=true;
                            break;
                        }
                    }
                    if (!okay) { 
                        alert("Please check a checkbox");
                        event.preventDefault();
                    } else {
                    }
                }
                -->
            </script>
        </form>
    </body>
</html>

사용하지 않는 것이 좋습니다.onsubmit스크립트에 이벤트를 첨부합니다.

var submit = document.getElementById("submitButtonId");
if (submit.addEventListener) {
  submit.addEventListener("click", returnToPreviousPage);
} else {
  submit.attachEvent("onclick", returnToPreviousPage);
}

그 후 사용preventDefault()(또는returnValue = false를 참조해 주세요).

function returnToPreviousPage (e) {
  e = e || window.event;
  // validation code

  // if invalid
  if (e.preventDefault) {
    e.preventDefault();
  } else {
    e.returnValue = false;
  }
}

이와 유사한 양식이 있다고 가정해 보겠습니다.

<form action="membersDeleteAllData.html" method="post">
    <button type="submit" id="btnLoad" onclick="confirmAction(event);">ERASE ALL DATA</button>
</form>

다음은 confirmAction 함수의 javascript입니다.

<script type="text/javascript">
    function confirmAction(e)
    {
        var confirmation = confirm("Are you sure about this ?") ;

        if (!confirmation)
        {
            e.preventDefault() ;
            returnToPreviousPage();
        }

        return confirmation ;
    }
</script>

Firefox, Chrome, Internet Explorer(엣지), Safari 등에서 사용할 수 있습니다.

그렇지 않으면 알려주세요.

예를 들어 폼에 submit 버튼이 있는 경우 propogation을 중지하려면 submit 버튼을 클릭하거나 Enter 버튼을 클릭했을 때 호출되는 함수에 event.proventDefault()를 입력합니다.

간단하게...

<form>
<!-- Your Input Elements -->
</form>

JQuery가 시작됩니다.

$(document).on('submit', 'form', function(e){
    e.preventDefault();
    //your code goes here
    //100% works
    return;
});

Hemant와 Vikram의 답변은 크롬에서 완전히 통하지 않았다.event.proventDefault(); 스크립트에 의해 검증 합격 여부에 관계없이 페이지가 전송되지 않았습니다.대신 다음과 같이 event.proventDefault();를 if문으로 이동해야 했습니다.

    if(check if your conditions are not satisfying) 
    { 
    event.preventDefault();
    alert("validation failed false");
    returnToPreviousPage();
    return false;
    }
    alert("validations passed");
    return true;
    }

헤만트와 비크람이 나를 올바른 길로 인도해줘서 고마워.

송신 버튼을 무효로 하면, 폼의 송신도 방지할 수 있습니다.

<input style="display:none" type="submit" disabled>

prevent default를 사용하여 제출을 차단한 경우 검증이 정상적으로 종료될 경우 폼도 제출해야 합니다.문서 유형을 확인하고 올바른 문서 유형인 경우 제출하는 완전한 예를 아래에 제시했습니다.

<h2>Document Upload</h2>
<script>
var CanContinue = false;

function validateMyForm()
{
if(CanContinue == false)
  { 
    alert("You must upload a PDF, PNG, or JPG of your document.");


return false;

  }
  document.getElementById("myForm").submit();

  return true;
}

function getFileNameWithExt(event) {

  if (!event || !event.target || !event.target.files || event.target.files.length === 0) {
return;
  }

  const name = event.target.files[0].name;
  const lastDot = name.lastIndexOf('.');

  const fileName = name.substring(0, lastDot);
  const ext = (name.substring(lastDot + 1)).toUpperCase();
    if (ext =="JPG") {
    extension.value = "image/jpeg";
    CanContinue = true;

} else if (ext =="JPEG") {
  extension.value = "image/jpeg";
  CanContinue = true;

} else if (ext =="PNG") {
  extension.value = "image/png";
  CanContinue = true;

} else if (ext =="PDF") {
  extension.value = "application/pdf";
  CanContinue = true;

} else {
  alert("You must upload a PDF, PNG, or JPG of your document.");
  CanContinue = false;
}

  outputfile.value = fileName;


}

</script>


                <form method="post" id="myForm" action="/wheregoing" enctype="multipart/form-data" onsubmit="event.preventDefault(); validateMyForm();">
                
                Please upload a JPG, PNG, or PDF of the front of the document.
                <input id='inputfile' type="file" name="dafile" onChange='getFileNameWithExt(event)' required>
               
             <input id='extension' type='hidden' name='ContentType' value="">
                <input type="submit">
                </form>

언급URL : https://stackoverflow.com/questions/8664486/javascript-code-to-stop-form-submission

반응형