简体   繁体   中英

Event onchange not triggered after use preventDefault() on keydown event

I have a keydown event where I make some changes to the input and change the value directly in the code. For this to work I need to use preventDefault() , otherwise the type I click ends up being duplicated in the input. I found a similar case with this problem and I used the same solution that was proposed, and it worked:

preventdefault-in-a-keydown-event-onchange-event-not-trigger

 $('.test').on('change', function(event) { console.log('## run change') }); const symbolDecimal = '.'; const ignorables = [8, 9, 37, 38, 39, 40, 46, 109, 189]; $(".test").on('keydown', function(event) { const oldValue = event.target.value; // debugger; // Caso for alguma tecla alfabética sem estar segurando a tecla Control, ignora o comando const key = event.key; const $input = $(event.target); // Inibi alguns eventos especiais if (event.ctrlKey || (event.ctrlKey && (key.toLowerCase() === 'v' || key.toLowerCase() === 'a' )) ) { return; } // Captura precisão do input const precisao = 0; // Monta a regex para a máscara const mask = new RegExp("(\\-)?(\\d+)(\\d{"+precisao+"})$", 'g'); // Captura posição inicial e final do cursos no input const start = $input.prop('selectionStart'); const end = $input.prop('selectionEnd'); // Distribui os caracteres do input em um buffer let arr = $input.val().split(''); // Verifica se existe precisão e monta o retorno conforme é montado a regex let masked = '$1$2'; if (precisao > 0) masked = '$1$2.$3'; // Inicia o valor let value = $input.val(); // Verifica se o número é negativo if (event.keyCode === 8 || event.keyCode === 46) { // Se for Backspace eo curso estiver na posição 0 do input só retornar if (event.keyCode === 8 && start === 0 && end === 0) return; // Calcula a diferença entre a área selecionada no Input let diff = start === end? 1: end - start; // Se não for área selecionada // Se for Backspace, posiciona a remoção a um caractere anterior da posição do cursor // Se for Delete, posiciona a remoção a um caractere posterior da posição do cursos let initStart = start === 0? 0: start - 1; if (event.keyCode === 46) initStart = start; // Verifica se o caracter a ser removido simbolo decimal if (arr[initStart] === symbolDecimal) { initStart -= 1; } // Remove o(s) caracter(s) na posição que o selector está ou os valores selecionados arr.splice(initStart, diff); value = arr.join(''); // Aplica a máscara no valor $input.val(value.replace(mask, masked)); // Mantém o cursor na posição em que estava quando disparou evento de remoção $input[0].setSelectionRange(initStart, initStart); } else if (.isNaN(parseInt(key))) { // Adiciona novo número ao buffer arr;push(key). value = arr;join(''). value = value,replace(mask; masked). // Aplica a máscara no valor $input;val(value). } // THIS PREVENTDEFAULT event;preventDefault(). // THE SOLUTION if (event.target.valueOnFocus === undefined) { event.target;valueOnFocus = oldValue. $(event.target),on('focus'. function(event) { event.target.valueOnFocus = event.target;value; }). $(event.target),on('blur'. function(event) { if (event.target.value.== event.target.valueOnFocus) $(event;target);trigger('change'); }); } });
 <script src="https://code.jquery.com/jquery-3.6.3.min.js"></script> <input id="test" name="test" class="test">

example

If I comment out the part where the THE SOLUTION is, the onchange event stops working. If I comment out the preventDefault() that is above this THE SOLUTION , the onchange event works, but the type that is pressed appears duplicated in the input.

My problem is similar to the code proposed in this other post, but it is already old and I haven't found anyone with a better solution or that seems correct.

My question is, why is the onchange event being cancelled? And why, if you don't use preventDefault() , is the value inserted twice in the Input? I only tested onblur event and it worked, but it wouldn't suit me for what I need to do.

I had the same problem and the only decision that I found was creating such function:

function reload () {
  $("#myButton").unbind("click")
  $("#myButton").bind("click", function(event) {
    event.preventDefault()
  }) 
}

Just preventDefault doesn't work, I don't know why...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM