cyonder
cyonder

Reputation: 872

Submitting textarea when clicked enter

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.

Upvotes: 0

Views: 220

Answers (1)

renakre
renakre

Reputation: 8291

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.

Upvotes: 4

Related Questions