Reputation: 73
I am trying to replace a div with another div onclick using the code below. It works fine for one instance. However, the problem is when the class appear more than once which is the case for me (multiple instances)it obviously changes all instance as they have the same class name. Is there a way to make it only change the clicked instance? Thanks
HTML
<div id="test"></div>
JavaScript (dynamically creating HTML)
var html =
'<form action="test.php" method="get" class="myForm">' +
'<input type="hidden" name="mID" value="' + this.id + '"/>' +
'<input type="image" class="send" src="this.image" name ="send" alt="submit"/>' +
'</form>';
$('div#test').append(html);
$("#test").on('click', '.send', function(e) {
e.preventDefault();
var $form = $(this).closest('form');
$.get($form.attr("action"),
$form.find(":input").serializeArray(),
function(data) {
$('.myForm').replaceWith('<div class="myForm2"><img src="Icons/PNG/tick 2.png" alt="submit"/></div></div>');
});
});
$("#test").on('submit', '.myForm', function(e) {
return false;
});
SOLUTION;
Instead of;
$('.myForm').replaceWith('<div class="myForm2"><img src="Icons/PNG/tick 2.png" alt="submit"/></div></div>');
CORRECT WAY;
$form.replaceWith('<div class="myForm2"><img src="Icons/PNG/tick 2.png" alt="submit"/></div></div>');
Upvotes: 1
Views: 93
Reputation: 28419
You're already most of the way there with $form = $(this).closest('form');
but for some reason you started selected all the forms instead by using $('.myForm')
, so
replace
$('.myForm').replaceWith(
...
with
$form.replaceWith(
...
Upvotes: 2
Reputation: 547
Simple! I am no JQuery Expert, but we doit the traditional way!
var elements = document.getElementByID('test') we would have elemements[0] and elements[1] .... everything with the id="test" inside. but only the first element needs to be replaces.
so, our choice falls on elements[0].
$('.myForm').replaceWith(.....)
take myForm away, and add the elements array number you'd like having to be replaces, then it's always this element in the doc that is being replaces.
have fun!
Upvotes: 0
Reputation: 131
$(".targetClass").click(function(){
var theDivBeingClicked = $(this);
//Do something
})
Upvotes: 0
Reputation: 2607
First of all, you are not replacing a div, you are replacing a form (with class .myForm
). As this form is inside the div you are clicking on when you want to change your form you could use:
$(this).find(".myForm").replaceWith...
Upvotes: 1