Javascript/HTML Onscreen keyboard working with input tag

问题内容:

I am trying to configure an onscreen keyboard that users can use to type things into an input element and when the length of the string inside of the input element exceeds 1 to carry out a specific function.

So far, i’ve got the following:

<form>
    <input id="search" type="text" onchange="livesearch(this.value)">
</form>

Which is the input element itself, which – onchange it executes the following function:

function livesearch(input){
    if(input.length > 1){
        alert(input);
    }
}

However, to input characters into the input element from the onscreen keyboard I am using the following:

document.getElementById('search').value += 'Q' 

The function livesearch is run after the length of the search box exceeds 1 and the user clicks the white space around the box, however it doesn’t work when text is input via the onscreen keyboard. I also want to fix the need for the user to click whitespace outside the element in order to carry out the function.

Any help would be much appreciated, any issues let me know.

问题评论:

2  
Changing the value with JavaScript does not trigger the events, you need to manually trigger it.

答案:

答案1:

The change event will not fire until the input looses focus. To achieve what you’re asking, you could do something like this (using jQuery):

$('input').on('change keyup paste', function() {
  console.log("Add your logic here...")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />

This will fire your code when the input is changed, the user releases a key (i.e. types), or when he pastes something into the input field.

答案评论:

    
Thanks for this, but unfortunately it’s for a university assessment and i’m banned from using jQuery (don’t ask why) but i’ve managed to make it work without it – but thank you so much for your help.
– Orbie
37 mins ago

原文地址:

https://stackoverflow.com/questions/47755486/javascript-html-onscreen-keyboard-working-with-input-tag

Add a Comment