Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
40
rated 0 times [  45] [ 5]  / answers: 1 / hits: 20284  / 13 Years ago, tue, april 26, 2011, 12:00:00

I need to run a search and replace on HTML similar to the following... I need to have Find Next Replace and Replace All options.... the trick is that I need to run an AJAX request to update the values in the database for each field once the value is replaced.



The only trouble I'm running into is that Im unsure exactly how to search the contents of #sheet and replace the values with the new value the user has provided.



<div id='sheet'>
<div class='item' id='field-18583'>This is yet another test</div>
<div class='item' id='field-18585'>This is test data</div>
</div>


I should say that it's possible I'll have TONS of text to search, so ideally I'd only find the next instance of the item that's being searched for, not all instances. So when I hit Find Next, if Im 3 items in, it'll go to the 4th.



What's the best way in javascript to maintain the indexing on this without storing all found results in a variable and causing lag on the page?


More From » jquery

 Answers
12

I would build a data object while traversing matched elements. Then send the object so you do not have multiple ajax request from a loop. jsfiddle:



<div class='item' id='field-18583'>This is yet another test</div>
<div class='item' id='field-18585'>This is test data</div>


Script:



var searchTerm = 'This is',
replaceWith = 'This is new',
updateObj = {};
$(#sheet div.item:contains(' + searchTerm + ')).each(function(){
// use id to build an update object
updateObj[this.id.replace('field-', '')] = {
oldText: searchTerm,
newText: replaceWith
}; // not sure what you are trying to save here
// manipulate html
this.innerHTML = this.innerHTML.replace(searchTerm, replaceWith);
});
// after, send ajax data `updateObj`

[#92553] Monday, April 25, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kamronr

Total Points: 749
Total Questions: 110
Total Answers: 122

Location: Dominica
Member since Sat, Nov 5, 2022
2 Years ago
kamronr questions
Mon, Dec 21, 20, 00:00, 4 Years ago
Fri, Oct 16, 20, 00:00, 4 Years ago
Sat, Oct 3, 20, 00:00, 4 Years ago
Sun, Jul 28, 19, 00:00, 5 Years ago
;