最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is there a method for adding both an onkeypress and onclick eventlistener together? - Stack Overflow

programmeradmin0浏览0评论

I have two questions, somewhat related.

1) is is possible to bine the 2 below functions into 1 more streamline function, or must I simply create a function and call it inside both eventlisteners

input.addEventListener("keyup", () => {
   if (event.keyCode === 13) {
     // code here 
}

and

input.addEventListener("click", () => {
     // code here 
}

but that would essentially be duplication of code

2) is there a way to make a sort of simple/basic autoplete menu (similar to google but nowhere near as powerful) based on the contents of an array? while typing in the input/search bar? For clarification, the w3schools example didnt work for me.

I have two questions, somewhat related.

1) is is possible to bine the 2 below functions into 1 more streamline function, or must I simply create a function and call it inside both eventlisteners

input.addEventListener("keyup", () => {
   if (event.keyCode === 13) {
     // code here 
}

and

input.addEventListener("click", () => {
     // code here 
}

but that would essentially be duplication of code

2) is there a way to make a sort of simple/basic autoplete menu (similar to google but nowhere near as powerful) based on the contents of an array? while typing in the input/search bar? For clarification, the w3schools example didnt work for me.

Share Improve this question edited May 1, 2019 at 5:24 Anan asked May 1, 2019 at 4:30 AnanAnan 8110 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

This is how you can attach multiple events to single element. For reference you can have a look at mozilladocs

var elem = document.querySelector('input')

elem.addEventListener('keyup', eventhandler, false);
//elem.addEventListener('click', eventhandler, false);// not sure about this event
elem.addEventListener('keydown', eventhandler, false);

function eventhandler(event) {
     if (event.keyCode === 13) { // you press enter you get alert 
     
        alert("hi");
     }
}
<input type="text" id="field">

Use a separate function that you call in both event listeners.

function doWhatIWant() {
    // code here
}

input.addEventListener("keyup", () => {
   if (event.keyCode === 13) {
     doWhatIWant();
}

input.addEventListener("click", () => {
     doWhatIWant();
}

You could try adding the onclick eventListener and/or keypress eventListener directly to the button and having the other in your javascript, with the code content you want to run in its own function.

<input type="text" id="input1" placeholder="searchbar">
<button id="button1" onclick=foo()>Search</button>
    function foo() {
      searchResult = document.getElementById("input1").value;
      // code here
    }

    const searchBar = document.getElementById("input1");
    searchBar.addEventListener("keyup", () => {
        if (event.keyCode === 13) {
          // executes the button click
          document.getElementById("myBtn").click();
        }
    });

As for the autoplete menu, I am unsure, but you could try turning it into a dropdown menu instead, however, this would likely make your need for the first part of the question invalid

For #1 in your question, the other answers seem sufficient.

Just as an alternative you could use some modern JS to write something that adds listeners for an array of event names, and handle them in your handler function like this:

// Handle keyup/click.
const handlerFn = e => e.type === 'keyup' ? e.keyCode === 13 && doSomething( e.type ) : doSomething( e.type );

// Did something.
const doSomething = type => console.log( `did something when ${type} triggered.` );

// Add handle/click listeners.
['keyup', 'click'].forEach( e => window.addEventListener( e, event => handlerFn( event ) ) );
Click in here, or press enter.

In terms of #2, and implementing #1, yes, it's possible to have a search triggered as you type using an array of data to filter through.

As a very basic implementation, I would suggest writing a function to handle finding matches via regex matches in JS. This could then be triggered from the keyup event, so it's filtered as a user types.

Here's an example of doing that with an input and search with some dummy data:

// Some data to filter/search while typing.
const thingsToFilter = [
	{
		title: "One one one title",
		description: "description for this one one one"
	},
	{
		title: "Number 2",
		description: "2 is two."
	},
	{
		title: "Another Thing",
		description: "description for another things"
	}
];

// Function to match searches.
const findMatches = (stringToMatch, thingsToFilter) => {
	return thingsToFilter.filter(function(thingToFilter) {
		var regex;

		// Search for the stringToMatch from thingsToFilter.
		regex = new RegExp(stringToMatch, "gi");

		// Returns matches based on title or description.
		return thingToFilter.title.match(regex) || thingToFilter.description.match(regex);
	});
};

// Setup event listener for typing in input.
const pageSearch = document.getElementById("search");
pageSearch.addEventListener("keyup", () => {
	let val = pageSearch.value;

	if (val) {
		let matched = findMatches(val, thingsToFilter);
		if (matched) {
			let markup = matched.map(result => `<div class="search-result">${result.title}:${result.description}</div>` ).join("");
			document.getElementById("search-results").innerHTML = markup;
		}
	}
});
<input type="text" id="search" placeholder="Search...">
<div id="search-results"></div>

发布评论

评论列表(0)

  1. 暂无评论