How to get the new value of an HTML input after a keypress has modified it?

后端 未结 6 1771
北恋
北恋 2021-02-05 03:24

I have an HTML input box


I\'ve attached a handler for the \'keyup\' event, but if

相关标签:
6条回答
  • 2021-02-05 03:48

    To give a modern approach to this question. This works well, including Ctrl+v. GlobalEventHandlers.oninput.

    var onChange = function(evt) {
      console.info(this.value);
      // or
      console.info(evt.target.value);
    };
    var input = document.getElementById('some-id');
    input.addEventListener('input', onChange, false);
    
    0 讨论(0)
  • 2021-02-05 03:56

    There are two kinds of input value: field's property and field's html attribute.

    If you use keyup event and field.value you shuld get current value of the field. It's not the case when you use field.getAttribute('value') which would return what's in the html attribute (value=""). The property represents what's been typed into the field and changes as you type, while attribute doesn't change automatically (you can change it using field.setAttribute method).

    0 讨论(0)
  • 2021-02-05 03:57

    Here is a table of the different events and the levels of browser support. You need to pick an event which is supported across at least all modern browsers.

    As you will see from the table, the keypress and change event do not have uniform support whereas the keyup event does.

    Also make sure you attach the event handler using a cross-browser-compatible method...

    0 讨论(0)
  • 2021-02-05 03:59

    You can try this code (requires jQuery):

    <html>
    <head>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                $('#foo').keyup(function(e) {
                    var v = $('#foo').val();
                    $('#debug').val(v);
                })
            });
        </script>
    </head>
    <body>
        <form>
            <input type="text" id="foo" value="bar"><br>
            <textarea id="debug"></textarea>
        </form>
    </body>
    </html>
    
    0 讨论(0)
  • 2021-02-05 04:05

    Can you post your code? I'm not finding any issue with this. Tested on Firefox 3.01/safari 3.1.2 with:

    function showMe(e) {
    // i am spammy!
      alert(e.value);
    }
    ....
    <input type="text" id="foo" value="bar" onkeyup="showMe(this)" />
    
    0 讨论(0)
  • 2021-02-05 04:09
    <html>
        <head>
            <script>
            function callme(field) {
                alert("field:" + field.value);
            }
            </script>
        </head>
        <body>
            <form name="f1">
                <input type="text" onkeyup="callme(this);" name="text1">
            </form>
        </body>
    </html>
    

    It looks like you can use the onkeyup to get the new value of the HTML input control. Hope it helps.

    0 讨论(0)
提交回复
热议问题