Dynamically add a keypress handler to an input

500
January 30, 2017, at 02:58 AM

I want to dynamically add a keypress handler to an input.

$("#m1rename").click(function() { 
  $('#modalinput').val('').keypress(function(event) { 
    if (event.keycode === 13) { 
      renameabc();  // this function name should be changed dinamically, based on `m1rename` click. 
    } 
  }); 
}); 
 
function renameabc() { 
  alert('abc'); 
} 
 
function renamedef() { 
  alert('def'); 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
<div id='modal'> 
  <form id='modalform' autocomplete='off'> 
    <input type='text' id='modalinput'> 
  </form> 
  <div class='modalbtn' id='modalok' onclick=''>OK</div> 
  <div class='modalbtn' id='modalcancel' onclick=''>CANCEL</div> 
  <div class='clear'></div> 
</div>

I want the alert to be shown if the Enter key is pressed inside modalinput, but it doesn't work.

Answer 1

If you want to dynamically add a key press listener to your input you can do like this:

$("#m1rename").click(function() {
  var funcName = $(this).val(); //this takes the value from m1rename. Use .text() if .val() don't work.
  $('#modalinput').val('').keypress(function(event) {
    if (event.keycode === 13) {
      funcName();  // this function name should be changed dinamically, based on `m1rename` click.
    }
  });
});
function renameabc() {
  alert('abc');
}
function renamedef() {
  alert('def');
}
Answer 2

try below code its working fine when you press enter key in textbox then it displays alert message.

    <html><head>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>  
$(document).ready(function(){
$("#modalinput").keypress(function(e) {
 if (e.keyCode == 13) {
    alert("You pressed a key inside the input field");
}
});
});
</script>
</head>
<body>
<div id='modal'>
<form id='modalform' autocomplete='off'>
<input type='text' id='modalinput'>
<div class='modalbtn' id='modalok' onclick=''>OK</div>
<div class='modalbtn' id='modalcancel' onclick=''>CANCEL</div>
<div class='clear'></div>
</div>
</form>
</body>
</html>
Rent Charter Buses Company
READ ALSO
Changing &lt;td&gt; value with js function? [duplicate]

Changing <td> value with js function? [duplicate]

This question already has an answer here:

300
500 POST internal server error ajax

500 POST internal server error ajax

I just started to learn AjaxI have situation in which when i call the ajax i have got this in my console

395
Appends only last value when looping through Json array Jquery

Appends only last value when looping through Json array Jquery

I am looping through a json array and append some of its value to a a divLooping through works fine

307
Passing value from a jquery slider into Django views.py

Passing value from a jquery slider into Django views.py

How can I pass a value selected from a jQuery slider into Django viewspy

444