user3392725
user3392725

Reputation: 65

onClick function inside a form with submit button causes error

When I use JavaScript button with onClick function inside the form tag in frontend.php, it causes mistake. I need this simple application that does simple job, but it got stuck at this.

I provide you two links. First is within the form tag (frontend.php) and there it doesn't work - ADDMORE BUTTON SIMPLY DOESN'T ADD MORE TEXTAREAS! And the second link is without the form tag, and it works, you can try and submit which will leave you to the welldone.php page.

1.LINK - There is a problem

2.LINK - No form tag, no problem

HTML FORM

<form action="http://www.balkanex.info/dev/frontend.php" method="post">
    Title: <br/><input type="text" name="title"><br/><br/>
    The question is: <br/><input type="text" name="ask"><br/><br/>
<br/>
    <input type="submit" name="submit" value="PROCEED"><br/>
</form>

FRONTEND.PHP FILE

<script>
am = 1;
function more(index) {
        am++;
        var textarea = document.createElement("textarea");
        textarea.name = "answer" + am;
        var div = document.createElement("div");
        div.innerHTML = textarea.outerHTML;
        document.getElementById("inner1").appendChild(div);
}
</script>

<?php
echo '<form action="welldone.php" method="post">';
$content = "";
$title = $_POST['title'];
$question = $_POST['ask'];

if($_POST['ask'] != "") {
    $answer = '<textarea name="answer1"></textarea>';
    $more = '<button type="button" name="more" onClick="more();">Add more</button>';
    $content .= '1) '.$question.'<br/>'.$answer.'<br/><div id="inner1"></div>'.$more.'<br/><br/>';
}
echo $content;
echo'<br/><input type="submit" value="CALCULATE"></form>';
?>

RESULTS WELLDONE.PHP FILE

<?php
echo 'WOW, WELL DONE';
?>

Upvotes: 1

Views: 1208

Answers (1)

Oriol
Oriol

Reputation: 288080

The problem is that, when you use more, browser is uses <button name="more"> instead of function more. Then, you get

TypeError: more is not a function

This behavior is only present in forms, that's why without forms your code works.

You can fix it doing one of these:

  • Changing function name
  • Changing button name
  • Writing unobtrusive javascript, adding the event handler from a <script> element instead ofthe inline onclick attribute.

Anyway, your code is completely invalid and in quirks mode. You should validate it and fix the errors.

Upvotes: 1

Related Questions