简体   繁体   中英

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).

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" );
})

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

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