Trying to rewrite, with minimal functional changes, a program that was written 10+ years ago. Taking it from aspx pages to .NET Core 3.0. For the most part, everything is straight forward. But here's the one problem I'm having - mainly because I'm not great with Javascript (and my searching online has yet to reveal the solution).
In the old system, to search for names, here was the process:
- Click a letter.
- Letter 'link' calls back to code behind.
- Code behind appends the new letter to a search string and then queries the database for the values.
- Code returns the records to a GridView.
So, all 26 letters are displayed in a row and are each a link. Each link gets handled by the same code behind function. To keep minimal functional changes (because the users want the same functionality), I'm going to keep all 26 letter links. However, rather than calling server code, I want to use javascript and ajax calls to accomplish as much as possible. Here's what I currently have:
HTML
<a id="addAToSearch" title="A" accesskey="A" onclick="addClickedLetter('A');">A</a>
<a id="addBToSearch" title="B" accesskey="B" onclick="addClickedLetter('B');">B</a>
<a id="addCToSearch" title="C" accesskey="C" onclick="addClickedLetter('C');">C</a>
<a id="addDToSearch" class="searchLetters" title="D" accesskey="D">D</a>
<a id="addEToSearch" class="searchLetters" title="E" accesskey="E">E</a>
Javascript
$(function () {
var searchLetters = document.getElementsByClassName("searchLetters");
for (i = 0; i < searchLetters.length; ++i) {
var letter = searchLetters[i].getAttribute('title');
searchLetters[i].addEventListener('click', function (letter) {
addClickedLetter(letter);
});
}
});
function addClickedLetter(letter) {
searchString = $("#txtSearchLastName").val() + letter;
$("#txtSearchLastName").val(searchString);
};
For the letters A, B, and C, when I click the links, they append to the string and it shows in the text box. However, rather than assigning the onclick
function in the HTML, I'd rather assign it dynamically. That's where D & E come in. I have code that iterates through elements with the searchLetters
class and assign their onclick
function. And it 'kind of' works. It does assign an onclick
function, but unfortunately both D & E do the same value: E. I assume that the code is retaining the last value letter
was set to and each onclick
that got set all use the same value.
What do I need to do to make sure the onclick function that is set retains the value at the time it was assigned?