First of all a note, the $('[name="search"]') will not select just the form but the input as well since it also has the same name value. So use $('form[name="search"]').
There are a couple of approaches to tackle your issue.
One is the answer of @pavel which re-writes the form html along with the new content.
Some problems with this approach are
- The exact posted code also suffers from the missing
form in the selector and will therefore remove the form tag from the result.
- if you later add some contents before the
form (in the same td) it will stop working (it will remove that content)
- if there are attached handlers on the form or any of its descendants, they will be lost, as
.html only keeps the html text and not anything attached through code.
- it will also not work directly with
.load. But you can work around that with $.ajax
Another more involved solution, but much safer, is to go through the pain of selecting the actual nodes after the form.
To do this you need to use .contents which is the only jQuery method that returns textNodes as well.
A verbose implementation (so you can see each step) could be
function replaceContentsAfterForm(newUrl) {
const form = $('form[name="search"]'); // select the form only
const formParent = form.parent(); // get the form container
const contents = [...formParent.contents()]; // select the contents of the container in an array
const formIndex = contents.indexOf(form[0]); // find where the form is in the array
const afterForm = contents.slice(formIndex + 1); // select everything after the form
const placeholder = $('<div id="placeholder" />'); // create a temporary placeholder to contain the data after the form
placeholder.append(afterForm); // fill the placeholder with the contents after the form
form.after(placeholder); // put the placeholder after the form in the DOM
$(placeholder).load(newUrl, function() { // load the new content
placeholder.replaceWith(placeholder.contents()) // and finally remove the placeholder eleemnt
})
}
// and you can call it with
replaceContentsAfterForm('new.php');
tdthere is nothing before theform. There are other rows before and after this one. I have no control over some of the code so can't add new elements etc.