Search code examples
javascriptjtextfieldjquery-eventskeycode

Pass the value of a textbox as a parameter to a Javascript function without submit button


I am writing because I have a problem with the passage of the value of a textbox without the submit button, but managing the event from the keyboard. The goal is to launch the function when I click the Enter key. I wrote this code, but for now it does not work:

 <form method="GET">
<input type="textfield"  id="testo_libero" onkeydown="javascript: if (event.Keycode==13) desc_ricerca(this.value);">
  </form>

In the Javascript file:

function desc_ricerca(valore){
     console.log("valore"+valore);
 }

Can anyone help me? I tried that but nothing ...

   function desc_ricerca(valore){    
     var cat = $("#testo_libero").val();
     console.log(cat);
   }

Solution

  • It seems like you're using jQuery. If so, you should look into using unobtrusive JavaScript. (You can write unobtrusive JavaScript even without jQuery, but jQuery makes it so much easier).

    For example, your code can be rewritten as follows:

    HTML:

    <form method="GET">
        <input type="textfield"  id="testo_libero">
    </form>
    

    jQuery:

    $('#testo_libero').on('keydown', function (e) {
        if (e.keyCode != 13) return;
        console.log('valore ' + this.value);
        return false;
    });
    

    Here's the fiddle: http://jsfiddle.net/wS5Db/