Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery AJAX submit by hotkeys

I'm trying to set "Ctrl+Enter" to execute function update:

document.onkeydown = function(e, id){
    var keyCode = (window.event) ? e.which : e.keyCode;
    if (keyCode == 13 && e.ctrlKey) {
        update(id);
    }
}
function update(id) {
    var title = $("#title"+id).val();
    var content = $("#content"+id).val();
        $.ajax({
            type: "POST",
            url: url,
            data: {
                aid: id,
                title: title,
                content: content,
            },
            beforeSend : function(){
                alert(content);
            },
            success: function(data){
                $("#view"+id).html(data);
            },

        });  
}

HTML part:

<input type="text" id="title<?php echo $id ?>" >
<textarea id="content<?php echo $id ?>" ></textarea>

It works with click event, but keypress. I tested with the above beforeSend and it returned undefined. What makes variable content become undefined? How could I fix it?

like image 374
Lewis Avatar asked Dec 02 '25 10:12

Lewis


1 Answers

I made a small, working example for you:

$(document).keydown(function(event)
  {
      var currKey=0,e=e||event; 
      currKey=e.keyCode||e.which||e.charCode;

      if (!( currKey == 13 && event.ctrlKey) && !(event.which == 19))
        {
            return true; 
        }    
      event.preventDefault();       
      alert("Ctrl + Enter was pressed"); // Replace this with your update(id);
      return false;
  }); 

Focus on input field in the following example and try pressing Ctrl+Enter to see it in action.

Online Demo

EDIT 1:

What made your content variable undefined is that its scope. You explicitly say var content and make its scope local, while trying to access it from another function.

Replace var content with content and you will get what you want!

Explanation:

JavaScript has two scopes: global and local. A variable that is declared outside a function definition is a global variable, and its value is accessible and modifiable throughout your program. A variable that is declared inside a function definition is local. It is created and destroyed every time the function is executed, and it cannot be accessed by any code outside the function. JavaScript does not support block scope (in which a set of braces {. . .} defines a new scope), except in the special case of block-scoped variables.

like image 176
Ilia Avatar answered Dec 04 '25 01:12

Ilia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!