1

I am trying to submit a form on keyup, sort of a keylogger effect. Here is my attempt -

php loop form -

<form method="post" id="'.$vid.'" class="note-form">
    <textarea id="'.$vid.'" name="quicknote" value="'.$quick_note.'" placeholder="add a quick note" class="quicknote">'.$quick_note.'</textarea>
    <input type="hidden" name="tac" value="'.$vid.'"/>
</form>

$vid is the unique id for each form that im passing from the DB.

JS file -

// Capture keyup from textarea to submit form

$('.quicknote').bind('keyup', function() { 
    var id = this.id;
    var formID = "#"+id;
    $(formID).delay(200).submit();
});
  
$(formID).submit(function(e) {
    var url = "ready-data/submit-note.php"; 
    $.ajax({
        type: "POST",
        url: url,
        data: $(this).serialize(),
        success: function(data) {
            // Do something
        }
   });
   e.preventDefault();
});

I use the same ID for the form and the inputs but the form isnt submitting. I can submit if I use the form class note-form but it submits all forms. I cant make formID a global variable to pass to the ajax function also. What is the correct way to do this?

1 Answer 1

1

Your form id and textarea id are same that's why its causing problem . Instead you can use $(this).closest('form') this will get closest form from textarea then you can submit only that form.

Demo Code :

$('.quicknote').bind('keyup', function() {
  var selector = $(this).closest('form') //get closest form
  $(selector).delay(200).submit(); //submit that.
});

$("form").submit(function(e) {
  console.log("data to send --> " + $(this).serialize())
  var url = "ready-data/submit-note.php";
  $.ajax({
    type: "POST",
    url: url,
    data: $(this).serialize(),
    success: function(data) {
      // Do something
    }
  });
  e.preventDefault();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" class="note-form">
  <textarea id="1" name="quicknote" value="somethings..." placeholder="add a quick note" class="quicknote">somethings..</textarea>
  <input type="hidden" name="tac" value="1" />
</form>
<form method="post" class="note-form">
  <textarea id="2" name="quicknote" value="somethings" placeholder="add a quick note" class="quicknote">somethings...</textarea>
  <input type="hidden" name="tac" value="2" />
</form>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.