artask
artask

Reputation: 439

How to get entered value after onkeydown?

I'm trying to get new value of an inputbox after entering each character if it's a number. But ajax in example below sends old value and not the newly entered value.

For example, if the value was 1 and I focused the inputbox, deleted the value and pressed 2, Ajax will send "1". But I need it to send "2"

HTML

<input type="text" class="quant-input" size="7" name="qty" value="1" onkeydown="change_qty();"/>

JavaScript

function change_qty(evt) {
    var charCode = event.keyCode
    if (charCode > 48 || charCode < 57) {
        jQuery.ajax("page.php", {
                type: "POST",
                data:'data='+$('.quant-input').val()
            });
        return true;
    } else {
        return false;
    }
}

Upvotes: 2

Views: 3691

Answers (5)

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92367

You can use onkeydown/onkeypress to make some validation before send ajax (to support copy-paste and special keys (e.g. Enter) you need additional code)

function change_qty() {
  let key = event.key;
  let oldval = event.target.value;
  let newval = oldval.slice(0,event.target.selectionStart) + key + oldval.slice(event.target.selectionEnd);
  
  console.clear();
  console.log("old value", oldval);
  console.log("new value", newval);

  // validation and ajax code

  // return false;   // will not allow to push key
  return true;       // will allow to push key
 
}
<input type="text" class="quant-input" size="7" name="qty" value="1" onkeydown="change_qty();"/>

Upvotes: 0

hitautodestruct
hitautodestruct

Reputation: 20820

Try these

Use either:

  1. Use onkeyup.
  2. Use the new html5 input event, in your case oninput:

    <input oninput="change_qty();" ...>
    

Check out this demo

A word on binding

You could and also should use binding for your event instead of an attribute:

Instead of: <input onkeyup="change_qty();">

Use:

$('.quant-input').keyup( change_qty );

Or

$('.quant-input').on( 'input', change_qty );

Upvotes: 0

user240141
user240141

Reputation:

You can try onBlur="change_qty();" that will give you the value after leaving focus from the control. Or if you dont dont want to leave the text box and needs the updated value the onKeyUp is fine

Upvotes: 0

Liauchuk Ivan
Liauchuk Ivan

Reputation: 1993

onkeydown

will call you function when user just press the button, so, first it will call you function, but then it will insert value in the input. So, you should use

onkeyup

Upvotes: 0

Ryan
Ryan

Reputation: 3926

The value isn't changed until the keyup event. So you need to use the following instead:

onkeyup="change_qty();"

Upvotes: 4

Related Questions