2011-08-22 17 views
4

我有一個表格;我已經改變了提交按鈕,只需鍵入「按鈕」這樣我就可以提交表單之前運行一些JavaScript代碼:在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 
    }); 
}); 

我在同一頁面上有很多這些表單,所以我需要相對引用表單和其他一些輸入。什麼是最好的方式來做到這一點?我正在考慮將一些前綴,這將是唯一的每個窗體,然後在選擇器中使用它,但這似乎很hacky ...

回答

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 
相關問題