Get the value of input text when enter key pressed

前端 未结 6 1335
温柔的废话
温柔的废话 2020-12-13 00:04

I am trying this:




        
相关标签:
6条回答
  • 2020-12-13 00:17

    Something like this (not tested, but should work)

    Pass this as parameter in Html:

    <input type="text" placeholder="some text" class="search" onkeydown="search(this)"/>
    

    And alert the value of the parameter passed into the search function:

    function search(e){
      alert(e.value);
    }
    
    0 讨论(0)
  • 2020-12-13 00:19

    Try this:

    <input type="text" placeholder="some text" class="search" onkeydown="search(this)"/>  
    <input type="text" placeholder="some text" class="search" onkeydown="search(this)"/>
    

    JS Code

    function search(ele) {
        if(event.key === 'Enter') {
            alert(ele.value);        
        }
    }
    

    DEMO Link

    0 讨论(0)
  • 2020-12-13 00:23

    You should not place Javascript code in your HTML, since you're giving those input a class ("search"), there is no reason to do this. A better solution would be to do something like this :

    $( '.search' ).on( 'keydown', function ( evt ) {
        if( evt.keyCode == 13 )
            search( $( this ).val() ); 
    } ); 
    
    0 讨论(0)
  • 2020-12-13 00:28

    Just using the event object

    function search(e) {
        e = e || window.event;
        if(e.keyCode == 13) {
            var elem = e.srcElement || e.target;
            alert(elem.value);
        }
    }
    
    0 讨论(0)
  • 2020-12-13 00:35

    Listen the change event.

    document.querySelector("input")
      .addEventListener('change', (e) => {
        console.log(e.currentTarget.value);
     });
    
    0 讨论(0)
  • 2020-12-13 00:40
    $("input").on("keydown",function search(e) {
        if(e.keyCode == 13) {
            alert($(this).val());
        }
    });
    

    jsFiddle example : http://jsfiddle.net/NH8K2/1/

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