Pooojaaaa
Pooojaaaa

Reputation: 179

Replace div after form submit

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#submit").click(function(){
    $("#p").replaceWith($("#p1"));
});
});
</script>
</head>
<body>
<div id="p">This is a paragraph.</div>
<div id="p1">Replacement</div>
<form action="" method="get">
<input type="submit" id="submit" name="submit" value="Search"/>
</form>
</body>
</html>

This code works fine until I put form action.. When I keep that submit in a form, this code does not work. How can i replace that div after form submit. Thanks.

Upvotes: 0

Views: 2867

Answers (5)

backpackcoder
backpackcoder

Reputation: 327

As Pooojaaqaa and Rayon mention the when the action attribute is set on the form tag, the form is submitted and the page is reloaded (even if action="#"). To catch this action you need to catch the form's submit event, not the button's click event. In the submit event handler you need to call preventDefault() on the event object passed into the handling function like below.

<form id="frmSearch" action="#" method="get">
   <input type="submit" id="submit" name="submit" value="Search"/>
</form>
$("#frmSearch").submit(function(ev){
    ev.preventDefault();
    $("#p").replaceWith($("#p1").text());
});

Upvotes: 0

Sandeep Sharma
Sandeep Sharma

Reputation: 136

Form submission needs to be done using AJAX then only you can achieve this which you want to do.

Otherwise the form will submit and page will refresh which will result to re initialization of script.

Upvotes: 0

HenryDev
HenryDev

Reputation: 4953

You can try this one. Hope it helps!

$(document).ready(function(){
$("#submit").click(function(event){
    $("#p").replaceWith($("#p1").text());
    return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="p">This is a paragraph.</div>
<div id="p1">Replacement</div>
<form action="" method="get">
<input type="submit" id="submit" name="submit" value="Search"/>
</form>

Upvotes: 2

Andre van Rensburg
Andre van Rensburg

Reputation: 161

Specify what to replace it with:

 $(this).replaceWith("<div><p>Replacement</p></div>"); 

Upvotes: 0

Mahi
Mahi

Reputation: 1727

you need text method for that . you were removing entire element before . you need to remove only text value

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#submit").click(function(){
    $("#p").replaceWith($("#p1").text());
});
});
</script>
</head>
<body>

<div id="p">This is a paragraph.</div>
<div id="p1">Replacement</div>

<input type="submit" id="submit" name="submit" value="Search"/>

</body>
</html>

Upvotes: 0

Related Questions