2013-05-29 2 views
1

내 웹 사이트의 일부 기능을 변경하려고합니다. 현재 테이블 외부에있는 유효성 검사 단추가 있습니다. 사용자가 해당 버튼을 클릭 할 때마다 유효성 검사가 수행됩니다.JavaScript - 'this.form'이 (가) 정의되지 않음을 반환합니다.

그러나 유효성 검사 단추가 제거되고 기능이 테이블 내부에있는 링크 단추로 이동되는 방식으로 변경하고 있습니다. 다음은

이 내 코드입니다 :

<table width="100%" cellpadding="4"> 
<tr> 
    <td valign="top"> 
     //something else here 
    </td> 
    <td valign="top" align="right"> 
     <asp:GridView ID="myGridView" runat="server" OnRowDataBound="myGridView_RowDataBound"> 
     <Columns> 
      <asp:TemplateField HeaderText="Column 1"> 
       <ItemTemplate> 
        // some control 
       </ItemTemplate> 
      </asp:TemplateField> 
      <asp:TemplateField HeaderText="Column 2"> 
       <ItemTemplate> 
        // some control 
       </ItemTemplate> 
      </asp:TemplateField> 
      <asp:TemplateField HeaderText="Column 3"> 
       <ItemTemplate> 
        // some control 
       </ItemTemplate> 
      </asp:TemplateField> 
      <asp:TemplateField HeaderText="Column 4"> 
       <ItemTemplate> 
        <asp:LinkButton ID="lbValidate" runat="server" Text="Validate" OnClientClick="return MyValidation__Submit(this.form)" CausesValidation="true" OnClick="btnValidate_Click"></asp:LinkButton> 
       </ItemTemplate> 
      </asp:TemplateField> 
     </Columns> 
     </asp:GridView> 
    </td> 
</tr> 
</table>  
<div style="margin:10px 0px 10px 0px;"> 
    <asp:Button ID="btnValidate" runat="server" Text="Validate" OnClientClick="return MyValidation__Submit(this.form)" CommandArgument="Save" CausesValidation="true" OnClick="btnValidate_Click" /> 
</div> 

그리고 여기에 검증을 수행하는 자바 스크립트 블록의 샘플입니다 :이 아주 잘 유효성 검사 버튼을 클릭하면 있지만 작동

<script type="text/javascript"> 
    function MyValidation__Submit(formName) { 
     alert("Test :" + formName); 
     // do validations 

     var joForm = document.getElementById(formName.id); 

     for (var i = 0; i < joForm.elements.length; i++) { 
      // do something 
     } 

     return true; 
    } 
</script> 

을 LinkButton에. 테스트를 위해 alert("Test :" + formName); 행을 넣어야했습니다. 유효성 검사 버튼을 누르면 시스템 경고는 "[object HTMLFormElement]"라는 문자열 값을 반환합니다.이 값은 원하는 방식으로 작동한다고 생각하면 좋습니다. 그러나 테이블 내부에있는 Validate LinkButton을 실행하려고하면 시스템 경고가 "undefined"를 반환하여 유효성 검사 코드 전체를 쓸모 없게 만듭니다.

누군가 내가 여기에없는 것을 지적 할 수 있습니까? 컨트롤의 계층 구조와 관련이있는 것으로 추측됩니다. 변경된 유일한 요소이므로 컨트롤의 계층 구조와 관련이 있습니다.

감사합니다.

편집 :

이 내가 갈 수 있지만 여전히 폼에 얻을 수없는 가장 먼입니다. 이것은 HTMLDivElement을 반환합니다.

<asp:LinkButton ID="lbValidate" runat="server" Text="Validate" OnClientClick="return MyValidation__Submit(this.parentNode.parentNode.parentNode.parentNode.parentNode)" CausesValidation="true" OnClick="btnValidate_Click"></asp:LinkButton> 

네, 그 권리를 읽었습니다. 그것은 5 .parentNode입니다.

+0

인증 코드를 볼 수 있습니까? 폼의 실제 이름이'formName' 인자로 기대 되었습니까?그렇다면 단순히'this.form' 대신'MyValidation__Submit (this.form.name)'을 쓰고 싶을 것입니다. – crush

+0

위의 편집을 참조하십시오. 기본적으로, 나는 formName을 사용하여 ID를 얻는다. 기존의 함수이기 때문에이 밸리데이션의 매개 변수를 실제로 변경할 수는 없으며이를 사용하는 다른 모듈을 망칠 수도 있습니다. – Smiley

+0

원하는 HTML을 생성하기 위해 ASP를 작성하는 데 문제가 있습니까? (최종 결과 대신 해당 질문을 표시하십시오.) 또는 생성 된 HTML과 JS가 상호 작용하는 방식입니다 (이 경우 생성 된 HTML을 보여줍니다. ASP가 아닌)? – Quentin

답변

0

[편집] 허용 대답이 마지막 예

당신은 단지하지 왜 페이지에 하나 개의 양식 요소를 가지고, 그래서 만약 당신이 jQuery를 사용한다고 가정입니까? 당신은 당신이 getElementsByTagName()

<script type="text/javascript"> 
    function MyValidation__Submit() { 
     // do validations 

     // getElementsByTagName("form") searches for any <form> elements on the page and returns an array of elements 
     // the [0] then selects the first one in the array that was found 
     // as long as you've only got one form on the page this should work 
     var joForm = document.getElementsByTagName("form")[0]; 

     for (var i = 0; i < joForm.elements.length; i++) { 
      // do something 
     } 
     return true; 
    } 
</script> 
으로 되돌릴 수는

<script type="text/javascript"> 
    function MyValidation__Submit(obj) { 
     // do validations 
     var joForm = $(obj).parents('form').eq(0); 
     for (var i = 0; i < joForm.elements.length; i++) { 
      // do something 
     } 
     return true; 
    } 
</script> 

을하고 jQuery를없이

OnClientClick="return MyValidation__Submit(this)" 

로 부를 수있는 하나 이상의 양식을 경우에도

<script type="text/javascript"> 
    function MyValidation__Submit() { 
     // do validations 
     var joForm = $('form').eq(0); 
     for (var i = 0; i < joForm.elements.length; i++) { 
      // do something 
     } 
     return true; 
    } 
</script> 

+0

감사합니다. 그러나 어떤 이유로이 둘 중 하나가 작동하지 않습니다. 'joForm' 선언 뒤에'alert (joForm);을 넣으려고했으나 시작되지 않습니다. 또한, 그 아래의 모든 것은 발사되지 않습니다. 어떤 생각이 잘못 될 수 있습니까? – Smiley

+0

더 많은 예제가 없으면 알기가 어렵지만 최근 브라우저를 사용하고 있다면 알아낼 수있는 도구가 있습니다. IE에서 귀하의 페이지에서 F12 키를 누른 다음 스크립트 탭에있어 당신이 Visual Studio에서 그들을 통해 단계 수없는 경우 거기에 자바 스크립트 오류가 나타납니다. Chrome과 Firefox에는 비슷한 개발자 도구가 있습니다. – Klors

+0

예, IE에서 디버깅을 시도하고 "Object expected"이라는 오류를 반환하고이 행을 가리 킵니다. var joForm = $ (obj) .parents ('form'). eq (0);' 솔루션과 정확히 같은 오류를 지적했다. 더 완전한 예를 무엇을 의미합니까? : S – Smiley

0

내 ASP 지식은 약간 초보이지만, "this.form"을 단추로 사용하면 "this"의 범위가 문서 개체이기 때문에 믿습니다. 그러나 귀하의 LinkButton에 사용되는 경우 "this"의 범위가 GridView입니다. 트리거 항목을 주변으로 이동하려는 경우 javascript 함수에 전달하는 formName을보다 명시 적으로 설정하는 것이 좋습니다.

+1

'this'는 버튼 자체를 나타냅니다. – crush

+0

안녕하세요, 정확히 내 생각이지만, 어떻게 계층 구조를 올라갈 수 있는지 정말 모르겠습니다. 폼을 반환하지만'[object HTMLTableCellElement]'를 반환하는'OnClientClick = "return JFFormScoreValidation__Submit (this.parentNode)"'으로 변경해 보았습니다. 이 문제를 어떻게 해결할 수 있을지 아십니까? 감사! – Smiley

관련 문제