0

First of all, there are many answers for this type of questions but none of them work for me because I am using multiple forms.

My question is, I need a script which will submit the data inside the textarea when clicked enter but the script must work with the code below.

<?php
    $inputValue = NULL;
    $id = "[1,2,3];"

    if(isset($_POST['inputName'])){
        $inputValue = $_POST['inputName'];
        echo "<br>Input Value: " . $inputValue;
    }

    if(isset($_GET['id'])){
        $getValue = $_GET['id'];
        echo "<br>Get Value: " . $getValue;
    }
?>

<html>
    <head>
        <title>Multiple Forms in One Page</title>
    </head>
    <body>

        <br>
        <a href="index.php">Main Page</a>
        <br>
        <?php for($i = 0; $i < 3; $i++){ ?>
        <form action="index.php?id=<?php echo $id[$i] ?>" method="post" name="formName">
            <textarea name="inputName"></textarea>
            <input type="submit" name="submitName">
        </form>
        <?php } ?>

    </body>
</html>

I used to use this one below, which doesn't work if there are multiple forms in one page.

<script>
    $(function() {
        $('textarea#inputName').on('keydown', function(e) {
            if(e.keyCode == 13 && !e.shiftKey){
                document.getElementById('formName').submit();
            }
        });
    });
</script>

Just to make it clear, If I create a single form in a page (like subscription for newsletter of a site) the script above will work. But if you have more than 1 form in a page (like facebook's comment boxes right after every post) the script above will not work. Thank you.

Ted
  • 14,757
  • 2
  • 41
  • 58
cyonder
  • 852
  • 1
  • 15
  • 36
  • `#inputName` implies there is an `ID` of that element. You only have a `name`. try `` ID's need to be unique. If you have more than one, you need to change to a `.class` – BReal14 May 01 '15 at 18:49

1 Answers1

4

How about this

  $(this).closest('form').submit();

instead of this

  document.getElementById('formName').submit();

In this way, only the form to which the current textarea belongs will be submitted.

renakre
  • 8,001
  • 5
  • 46
  • 99