0

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();
1
  • What you've tried till now, add code in your question Commented Oct 13, 2018 at 12:03

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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();

Comments

0

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.