chiboz chiboz - 7 months ago 23
HTML Question

How to Replace a Div with another Div but only once

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>');

Answer

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(...