onchange event for input type=“number”

前端 未结 10 1772
梦如初夏
梦如初夏 2020-12-02 22:11

How can I handle an onchange for ? I can\'t do a keyup or keydown, be

相关标签:
10条回答
  • 2020-12-02 22:31

    There may be a better solution, but this is what came to mind:

    var value = $("#yourInput").val();
    $("#yourInput").on('keyup change click', function () {
        if(this.value !== value) {
            value = this.value;
            //Do stuff
        }        
    });
    

    Here's a working example.

    It simply binds an event handler to the keyup, change and click events. It checks whether or not the value has changed, and if so, stores the current value so it can check again next time. The check is required to deal with the click event.

    0 讨论(0)
  • 2020-12-02 22:33

    I had same problem and I solved using this code

    HTML

    <span id="current"></span><br>
    <input type="number" id="n" value="5" step=".5" />
    

    You can add just 3 first lines the others parts is optional.

    $('#n').on('change paste', function () {
        $("#current").html($(this).val())   
    });
    // here when click on spinner to change value, call trigger change
    $(".input-group-btn-vertical").click(function () {
       $("#n").trigger("change");
    });
    // you can use this to block characters non numeric
    $("#n").keydown(function (e) {
        // Allow: backspace, delete, tab, escape, enter and .
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 || (e.keyCode === 65 && e.ctrlKey === true) || (e.keyCode >= 35 && e.keyCode <= 40)) 
               return;
    
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) 
           e.preventDefault();
    });
    

    Example here : http://jsfiddle.net/XezmB/1303/

    0 讨论(0)
  • 2020-12-02 22:34

    Use mouseup and keyup

    $(":input").bind('keyup mouseup', function () {
        alert("changed");            
    });
    

    http://jsfiddle.net/XezmB/2/

    0 讨论(0)
  • 2020-12-02 22:36

    To detect when mouse or key are pressed, you can also write:

    $(document).on('keyup mouseup', '#your-id', function() {                                                                                                                     
      console.log('changed');
    });
    
    0 讨论(0)
提交回复
热议问题