0

I have an input text and I want to run my function after the default event handler

<input type="text" onkeypress="myfunction()"></input>

the function

function myfunction(){alert($("input")[0].value)}

because myfunction() is using the input value and this property will be changed after the default handler runs and change it. Example: if the text field has value "1234" , and I pressed the key "5", the function will alert "1234" not "12345"

So, I want the default function runs first to change the value property , then I can use it in myfunction()

can I do something like this ?!

 onkeypress="default();myfunction()"

I did a work around by putting myfunction() in the onkeyup event, but I don't want that.

Thanks, and please consider I'm very newbie.

Accountant م
  • 6,975
  • 3
  • 41
  • 61

1 Answers1

1

TRIVIAL SOLUTION:

You should use oninput instead of onkeypress. Like so:

<input type="text" oninput="myfunction(event)" />

The keypress event is emitted when a key gets pressed, i.e., before the DOM is modified with the pressed key's value. This is why you never got the value of the last key pressed.

The input event is emitted when data is entered into the input element. So we can access the data by reading the value of the element.


USING EVENT-BINDING:

  1. HTML

<input id="input_field" type="text" />

  1. jQuery
$(document).ready(function() {
    $("#input_field").on("input", function() {
    console.log($(this).val());
  });
});
  1. Pure JS
    var input_field = document.getElementById("input_field");
    input_field.addEventListener("input", function(event) {
        console.log(event.target.value);
    });

NOTE: Add this in a script tag after the HTML or use window.onload to simulate the behaviour of $(document).ready.

See this SO answer for more information about how event-binding works.

Community
  • 1
  • 1
Soubhik Mondal
  • 2,666
  • 1
  • 13
  • 19