I tried using the "input" event on the text box but it doesn't work. I've read a few posts on Stack Overflow but none of them worked.
Here's my most recent HTML and Javascript code using onchange:
function updateResults(){
document.write("Wroks");
}
<input id="search-box" onchange="updateResults();"> </input>
I tried changing HTML to onchange="updateResults;" but didn't work.
I also tried changing HTML to onchange="updateResults(event);" and then Javascript to function updateResults(event){...}
Nothing that I tried worked.
Looks fine to me. If you make any changes then you'll see the function get called as soon as you lose focus (onchange only happens when you blur). If you want more immediate results you can use oninput instead, like so:
function updateResults(){
document.write("Wroks");
}
<input id="search-box" oninput="updateResults();" />
Another way is to use event listeners, if you want to keep javascript out of the markup:
function updateResults() {
document.write("Wroks");
}
document.getElementById("search-box").addEventListener("input", updateResults);
<input id="search-box" />
The above however will only work if the DOM has already been loaded when the javascript is run. You could put it in an onload event, or include the javascript after the DOM markup.
Alternatively you could attach the event listener to the document and check for the ID whenever the event is triggered. There are pros and cons to this method. Since the function doesn't attach to the element directly, the DOM will not need to be loaded yet. If the element is removed and a new one with the same ID is added, it will still work. Also, if you add your content dynamically after the page loads, you will not need to worry about attaching the listener later. However, this function will be called every time any input on the page is registered, which theoretically could slow the page down (e.g. if you have a lot of these types of listeners), although probably minimally.
function updateResults() {
document.write("Wroks");
}
document.addEventListener("input", function(e) {
if (e.target.id === "search-box") {
updateResults();
}
});
<input id="search-box" />
document.write("Wroks"); will replace everything in your window with "Wroks".
try this:
<input id="search-box" onchange="updateResults();"> </input>
<script>
function updateResults(){
console.log('Works');
}
</script>
You also may want to consider using jQuery because then you could do a lot more out of the box with this. for example:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<input id="search-box">
<script>
$('#search-box').on('change',function(){
console.log($(this).val());
})
</script>
The above code will give you the value of the input on change.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With