How to properly clear a search input upon cliking on a list of links

I know the current code is bad practice because is too generic, but how can I make it better?
Context: im targeting a set of links with JS, and need to clear/ remove user input in a search box upon click on any of those links.

function clearSearchInput(event) {    
    document.getElementById("searchbox").value = "";  
};

var links = document.getElementsByClassName("mystyle");

for (var z = 0; z < links.length; z++) {
    links[z].addEventListener('click', clearSearchInput );
}

Honestly, this code works just fine. The only thing it wouldn’t help with is if any of the elements with a mystyle class are dynamically put on the page (as in a data driven web app), which you’d have to do a bit more to not have to rebind a click event to every single element every time. But if those elements are loaded from page load and don’t change, this works perfectly!

1 Like

One option would be to define this

as global variable, so if needed you can refer to it in other parts of code

1 Like

Thank you for the input :slight_smile: Question should this code cause problems if other click event listeners target those? What are the good code practices about it? I should had mentioned I started to wonder because in mobile this list of links actually don’t go to the link referenced anchor position when a filter is in place… so clicking once removes the search input/and the filtered links, but it doesn’t as well go to the anchor unless a do a second click once the search is removed.

Ideas: I was playing with

function clearSearchInput(event) {    
    document.getElementById("searchbox").value = "";
    idSroll = event.target.id;
    document.getElementById(idScroll).scrollIntoView();
               
};

in order to force the jump, but is not recognizing the id .

you have typo here
idSroll and idScroll

can’t see anything bad about having more functionality inside same event handler

since two thingies should happen while the same event occurs - they can live inside one event handler

1 Like

Oh my ty!!

and if they are separated in two events handlers?
I also had this code in use:

document.querySelector('a[href=\"' + window.location.hash + '\"]').click();

Getting this error though on the getElementById :confused:

Empty string passed to getElementById().

Update the target didn’t contain the id instead the href did this worked nicely (at least shows up the correct id in the console:

idScroll = event.target.href;
    idScroll2 = idScroll.slice(idScroll.indexOf('#') + 1);

But even there I can’t scroll in some cases.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.