Search code examples
javascripthtmlkeyboarddom-events

Javascript Keyboard Event change marked text


I have an input field which looks like this:

<input type="text" name="definemonth" value="'.$monthStart.'" class="form-control"
onkeypress="return isNumberKey(event, this.value);" />

To allow only numbers between 1 and 28 (each included) I wrote this piece of JS code:

var input = event.key;
var newValue = value + input;

if(input == "ArrowLeft" || input == "ArrowRight" || input == "ArrowUp" ||
   input == "ArrowDown" || input == "Backspace" || input == "Delete" || input == "Enter")
{
    return true;
}

if (!input.match("^[0-9]$") || newValue > 28 || newValue < 1)
{
    return false;
}

return true;

It works mostly as I want it to. I want to be able to use the Arrow Keys, the backspace and delete button which works all just fine. But the issue is that I can not mark the text and then add a new number. With marking I mean this kind of marking: enter image description here The marking works fine but any key stroke does not change anything at all.

I tried to detect with

console.log(input);

what happens there but I do not get any output in the console at all.

My question is then how do I have to change my code to be able to enter a new value when the text is marked and I type 1 for example.


Solution

  • You should clear selected text before checking new value for allowability.

    Like this:

    var clearValue = element.value;
    clearValue = clearValue.slice(0, element.selectionStart) + clearValue.slice(element.selectionEnd);
    
    var newValue = clearValue + input;
    

    jsfiddle