user1125033
user1125033

Reputation: 35

jquery selecting values from identical forms

I am teaching my self php and mysql.I am creating a small commerce site to test my skills. I have mutiple forms on page like this

<div class="formInfo"><form name="CartForm" method="post" action="./ajax/addCart.php" class="fixed">
<input name="prodId" type="hidden" value="10" />
  <label for="qty">Quantity:</label>

  <input name="qty" type="text" id="qty" size="4" maxlength="6" class="qtyBox">
  <br>
  <input type="submit" name="addtoCart" id="addtoCart" value="Add to Cart" class="btnAdd">
</form>



<div class="formInfo"><form name="CartForm" method="post" action="./ajax/addCart.php" class="fixed">
<input name="prodId" type="hidden" value="7" />
  <label for="qty">Quantity:</label>

  <input name="qty" type="text" id="qty" size="4" maxlength="6" class="qtyBox">
  <br>
  <input type="submit" name="addtoCart" id="addtoCart" value="Add to Cart" class="btnAdd">
</form>


<div class="formInfo"><form name="CartForm" method="post" action="./ajax/addCart.php" class="fixed">
<input name="prodId" type="hidden" value="9" />
  <label for="qty">Quantity:</label>

  <input name="qty" type="text" id="qty" size="4" maxlength="6" class="qtyBox">
  <br>
  <input type="submit" name="addtoCart" id="addtoCart" value="Add to Cart" class="btnAdd">
</form>

Now when I click sumbit button I want to show the values of hidden field id and visible field qta (of currently clicked form) so far my code is

<script type="text/javascript">
$(document).ready(function(e) {
    $('.formInfo').submit(function() {
        alert($(this).val())
    });
});
</script>

I can not figure out.How to tell jquery that I want values of "id" and "qty" of 'this' reference not the value of reference itself

Upvotes: 0

Views: 131

Answers (2)

Musa
Musa

Reputation: 97727

As stated in previous answers ids should be unique, you need to bind submit to the form not a div, you can access form members by their name from the form element

$(document).ready(function(e) {
    $('.formInfo form').submit(function() {
        alert(this.prodId.value);
        alert(this.qty.value);
    });
});

FIDDLE

Upvotes: 0

wecsam
wecsam

Reputation: 2771

First of all, you can't have more than one element in the same HTML document with the same id. You'll have to change those to something like qty1 and qty2. You're binding the event to the <div>, not the form. You also need to select the input elements. Try this:

$(document).ready(function(e) {
    $('.formInfo form').submit(function() {
        $("input[type=hidden],input[name=qty]",this).each(function(){
            alert($(this).val());
        });
    });
});

Upvotes: 1

Related Questions