Keep selected record on page during search

Keep selected record on page during search

Loren MaxwellLoren Maxwell Posts: 378Questions: 92Answers: 10
edited August 2023 in Select

I've tried doing this a couple of different ways without success, but I'd like to set the current page of a search to the one with a selected record if there is one.

For example, using the Select initialization example: https://www.datatables.net/extensions/select/examples/initialisation/simple.html

1) Go to Page 6 and select "Zorita Serrano"
2) In the search type "S" for San Francisco

The table is reset to the first page of the search results and the selected record goes to the second page.

I've tried to use the (excellent) row().show() plugin or the plan old page() on the search but then it requires a draw(), which in turn triggers another search, which triggers another draw(), etc., causing an overflow.

Although this ability would be helpful overall, it would be particularly useful when using DataTables as an input so that it is highlighted to the user that there is already a selection made even though they are searching.

Any suggestions that would help me escape that search draw() loop?

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 19,891Questions: 26Answers: 4,691
    edited August 2023 Answer ✓

    I think the problem is with order of operations with the search and draw events. This is a non working example but the point is to look at the order of events:
    https://live.datatables.net/xaroqiji/1/edit

    The test case selects Tiger Nixon. Type e to search for Edinburgh. In the console you will see this:

    Num selected rows:  1
    draw
    draw
    

    I believe the first draw is from .show().draw('page') and the second is called after the search event fires - negating the row().show() statement. Not 100% sure, just my speculation.

    Here is a working example:
    https://live.datatables.net/yedegako/1/edit

    It uses jQuery one() to create a one time event handler.

    Use the same steps for this output:

    Num selected rows:  1
    draw
    draw one time
    draw
    

    I think the first draw is happens after the search event. Then the one time handler executes and the last draw is from the .show().draw('page').

    Note the use of the page parameter for draw() to keep from applying searching and ordering.

    Kevin

  • Loren MaxwellLoren Maxwell Posts: 378Questions: 92Answers: 10

    @kthorngren -- Kevin, you're such as badass! This is the second time you've pointed me toward jQuery .one() and I admit I didn't really study it well enough the first time.

    It works like a charm!

Sign In or Register to comment.