saluyotamazing saluyotamazing - 8 days ago 6
Ajax Question

How can I show a single instance of a div using jquery? (AJAX, jQuery)

I have an array of forms that has a success message on each. I want to show a success message on the form that is clicked only. However, the success message on all forms are showing whenever I click on a single form. Forgive me for my question as I am a beginner in javascript and jquery. How can I achieve this? Here is my html code...

<c:forEach items="${inventories}" var="inventory" varStatus="varStatus">
<div class="col-xs-6 col-sm-3" style="padding: 2%;">
<div class="card">
<img class="card-img-top"
src="${pageContext.request.contextPath}/image?prodId=${inventory.getProduct().getProductId()}"
alt="Card image cap"
style="height: 200px; width: 100% px; display: block; margin: auto;">
<form:form id="add_to_cart_form" action="addToCart" method="POST"
modelAttribute="cartProduct">
<form:input type="hidden" path="user.email"
value="${user.getEmail()}" />
<form:input type="hidden" path="product.productId"
value="${inventory.getProduct().getProductId()}" />
<div class="card-block" style="overflow: hidden; padding: 2%">
<h5 style="white-space: nowrap">
<a href="#" class="text-primary card-title">${inventory.getProduct().getName()}</a>
</h5>
<p class="card-text text-danger">&#8369;
${inventory.getProduct().getPrice()}</p>
<p class="text-success">In stock</p>
<p>
<div class="success-message" style="display: none;"><span class="text-success add-to-cart"><strong>Added
to cart!</strong></span></div>
</p>
<form:button class="btn btn-block btn-warning">Add to cart</form:button>
</div>
</form:form>
</div>
</div>
</c:forEach>


And here is my AJAX code...

$(document).ready(function() {

var form = $("form");
var url = form.attr("action");
var formMethod = form.attr("method");

form.submit(function(event) {

event.preventDefault();

$.ajax({

url : url,
data : $(this).serialize(),
type : "POST",
success : function(cartProduct) {
$('.success-message').show();
}
});
});
});

A.J A.J
Answer

Try storing reference of form submitted in variable and then find the success-message in the form that was clicked and show it.

Reference code:

$(document).ready(function() {
  var form = $("form");
  var url = form.attr("action");
  var formMethod = form.attr("method");
  form.submit(function(event) {
    var that = this;   //store reference of form submitted in variable
    event.preventDefault();
    $.ajax({
      url: url,
      data: $(this).serialize(),
      type: "POST",
      success: function(cartProduct) {
        $(that).find('.success-message').show(); //find the success-message in the form that was clicked and show it
      }
    });
  });
});