0

I have code that looks like this:

<?php
    for ($i = 0; $i < count($keyArray); $i++) {
?>
<form action="" method="POST">
    <th>
        <a href="#" onclick="$(this).closest('form').submit()">
        <?php echo $keyArray[$i] ?></a>
    </th>
    <input type="hidden" name="tableHeader" value="<?php echo $keyArray[$i]; ?>">
</form>
<?php } ?>

I'm trying to submit the form through a link. To test the form, I use:

echo "<pre>";
print_r($_POST);
echo "</pre>";

I've tried using a button type submit, and it works. I don't know what's wrong with the jQuery in my onclick, but the info is not being sent.

8
  • Why don't you just do onclick="this.form.submit()" Commented Jul 11, 2013 at 19:52
  • Maybe the link is put somewhere else (outside the form) because you are generating invalid HTML. A th element cannot be the child of a form element. Commented Jul 11, 2013 at 19:52
  • My guess is that $(this).closest('form') is not fetching any form... Commented Jul 11, 2013 at 19:53
  • could always HTMLInputElement.form, e.g. onclick="this.form.submit()" Commented Jul 11, 2013 at 19:54
  • I also tried giving an id to the form and it didn't work either. Basically what I want to do is sorting the table records when people click on a table header. If I have invalid HTML, what alternative could I be using? Commented Jul 11, 2013 at 19:55

2 Answers 2

1

May be if you give an ID to your form and using it in your jQuery command :

<form id="form<?php echo $i ?>" action="" method="POST">
<th><a href="#" onclick="$('#form<?php echo $i ?>').submit()"><?php echo $keyArray[$i] ?></a></th>
<input type="hidden" name="tableHeader" value="<?php echo $keyArray[$i]; ?>">
</form>
Sign up to request clarification or add additional context in comments.

2 Comments

@jSmith: If this works, then the problem really is your invalid HTML. Just fix the HTML and your code will work as well.
Right Felix. I'd chose you as best answer now because this simple modification makes it work. (Simply moving the th's outside the form).
1

Why you dont just add a submit button instead of an anchor with a jQuery trigger ?

<input type="submit" id="submit-btn" value="<?php echo $keyArray[$i] ?>">

If you want it like an anchor, you can use CSS :

#submit {
    background: transparent;
    color: blue;
}

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.