jedierikb
jedierikb

Reputation: 13099

intercept html5 number input before rendering?

I want to intercept input change events before the value is rendered to the screen. This would be useful for prepending zeroes. However, this is not working.

<html>
<body>
<input id="tc" type="number" value="100"></input>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$("#tc").on( 'change', function() {
  $("#tc").val( "12" );
})
</script>
</html>

Neither is listening on requestAnimationFrame and changing the value. What do do?

Fwiw, this works in Safari (but not Chrome and Firefox).

Upvotes: 0

Views: 362

Answers (2)

Razvan
Razvan

Reputation: 3142

Subscribe on keydown.

$("#tc").on( 'keydown', function(event) {
    event.preventDefault();
    $("#tc").val( "12" );
});

Or if you want from all the input sources subscribe for input:

$("#tc").on( 'input', function(event) {
  $("#tc").val( "12" );
})

Upvotes: 2

Pete
Pete

Reputation: 133

First you need to set the value with $("#tc").val( "12" ); and use .on('change') when they change the value.

$("#tc").val( "0.00" );
$("#tc").on( 'change', function() {
    var n = $(this).val()
    $("#tc").val(n + ".00" );
});

Heres a jsFiddle example

Upvotes: 0

Related Questions