2011-08-22 3 views
4

나는 아래 양식이 있습니다; 여기 jquery에서 어떻게 현재 양식을 클릭하여 클릭하여 참조 할 수 있습니다

<form action="/Cart" method="post"> 
    <input type="hidden" name="name" value="12" /> 
    <input type="button" class="addToCartButton" value="Add to Cart" /> 
</form> 

내 초기 이벤트 핸들러 :

나는 내가 형태로 제출하기 전에 몇 가지 자바 스크립트를 실행할 수있을 것입니다 그래서 그냥 "버튼"을 입력 버튼을 제출 변경 : 내 양식 여기

입니다

$(document).ready(function() { 
    $('.addToCartButton').click(function() { 

     //need to reference current form here 
     //need to reference the hidden input with name="Name" above 
    }); 
}); 

같은 양식에 여러 개의 양식이 있으므로 양식과 다른 입력 양식을 상대적으로 참조해야합니다. 그것을하는 가장 좋은 방법은 무엇입니까? 각 양식에 고유 한 일부 접두사를 넣은 다음 선택기에서 해당 접두사를 사용하는 것으로 생각했지만 매우 익숙한 것 같습니다 ...

답변

10

이 작동합니다 :

$(document).ready(function() { 
    $('.addToCartButton').click(function() { 

     //need to reference current form here 
     $(this).closest('form'); 
     //need to reference the hidden input with name="Name" above 
     $(this).closest('form').find('input[name="name"]'); 
    }); 
}); 
4

jQuery closest()가 트리를 이동하여 선택은 :

$(this).closest("form"); 
+0

htanks을 빠른 응답. 양식 안의 다른 숨겨진 필드를 참조하는 방법은 무엇입니까? (이제는 참조가 있습니다) – leora

+0

다른 사람들이 지적했듯이, 여러분이 가고 싶을지라도'find ('input [name = "name"]')' 이름보다 설명이 가치있는 이름으로, 아마도 formName입니까? – Dennis

1
$('.addToCartButton').click(function() { 

     //need to reference current form here 
     var the_form = $(this).closest("form"); 

     //need to reference the hidden input with name="Name" above 
     var the_input = the_form.find('input[name="name"]'); 
    }); 
3
$(this).siblings("input[name='name']"); // the field 
$(this).closest("form"); // the form 
관련 문제