2

I have a page of products and for each of them, I want to have a form that uses AJAX to update the session. I've done this bit - just providing background.

I use the product's ID to create a different form class and name for each form, so each form is called something like this_form_name_567 and the next would be this_form_name_568 and so on.

There is a submit button per form. I'm having trouble figuring out

  1. Which event is best to use so that the correct form will be identified when a submit button is clicked?

  2. Once clicked, how to then make sure the correct value is taken from a hidden field (unique ID) within the submitted form so that I can populate a line of code such as:

    $.post("compare_response.php", {compare_this: $("#compare_this").val()}, function(data){
    }
    
Michael Mrozek
  • 169,610
  • 28
  • 168
  • 175

2 Answers2

2

You can use the .closest tree traversal method to get the form in which the button of interest is nested:

$("input[type=submit]").click(function() {
    alert($(this).closest("form").attr("id"));
});

or even simpler, just get the element's form property :)

$("input[type=submit]").click(function() {
    alert(this.form.id);
});

You can try it out here.

karim79
  • 339,989
  • 67
  • 413
  • 406
1

You can get the form you are submitting like this:

$('form').submit(function() {
    var yourForm = $(this);
    var hiddenValue = $(this).find('input[type=hidden]').val();
});

Of course you can get the hidden value differently, or if you have more than one hidden you'll have to give a little more information about it.

Jeremy B.
  • 9,168
  • 3
  • 45
  • 57