Reputation: 232
To demonstrate what I want to do I use an example from W3schools here in codepen.
I have a text box that has a keyup
event listener, with each character you enter it refines your search.I want to fill the textbox with text using value
property of it and then trigger the keyup event so that the keyup event listener runs.
But I couldn't get anything to do just that.
I want to use core JS but to test it I tried it with jQuery too but no luck.
$('#mySearch').val("j");
$('#mySearch').keyup();
Upvotes: 0
Views: 4367
Reputation: 1
As discussed here
You can use fireEvent on IE 8 or lower, and W3C's dispatchEvent on most other browsers. To create the event you want to fire, you can use either createEvent or createEventObject depending on the browser.
Here is a self-explanatory piece of code (from prototype) that fires an event dataavailable on an element:
var event; // The custom event that will be created
if(document.createEvent){
event = document.createEvent("HTMLEvents");
event.initEvent("dataavailable", true, true);
event.eventName = "dataavailable";
element.dispatchEvent(event);
} else {
event = document.createEventObject();
event.eventName = "dataavailable";
event.eventType = "dataavailable";
element.fireEvent("on" + event.eventType, event);
}
Upvotes: 0
Reputation: 25
As Math already stated, you can create a function that runs as per key press (or release in your case). The function should refine the search. I would recommend JS for this, but if you want to use jQuery, then here is what you could do:
$("#mySearch").on("keyup", function()
{
// Refine search here
});
Or alternatively, you could just use the .keyup()
function:
$("#mySearch").keyup(function()
{
// Refine search here
});
Hope this helps
Upvotes: 1
Reputation: 38
Instead of trying to trigger the keyup event programmaticaly, you can call the function you assigned to it. So in core JS you would have :
In the HTML :
<input id="mySearch" type="text" onkeyup="myFunction()">
In the JS you create the function myFunction witch will refine you search. And when you want to change the value of your input you can call to function just after the change :
function myfunction() {
//refine search code
}
//change the value of the input
document.getElementById('mySearch').value = "j";
myFunction();
Upvotes: 0