-2

I am a beginner in JavaScript and HTML. I am trying to prevent buttons from submitting forms. It is not working with my below code. It is working when I remove the type:button and return false in the code but if I remove it is always submitting the form.

<!DOCTYPE html>
<html>
<head>
    <title>Font Awesome Icons</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
    <button type="button" onclick="myFunction1();return false;" style="font-size:24px">Button <i class="fa fa-info-circle"></i></button>

    <script type="text/javascript">
        function myFunction1(){

        }
</body>
</html>
krlzlx
  • 5,752
  • 14
  • 47
  • 55
laika
  • 11
  • 1

2 Answers2

-1

JQUERY

You should be able to do:

$('#formid').submit(false);

or

$('#formid').submit(function(e){ e.preventDefault(); });

To use the jquery library visit the official website http://jquery.com/download/

PURE JS

document.getElementById('formid').addEventListener('submit', function(e) {
    e.preventDefault();
});
Fobos
  • 1,076
  • 8
  • 18
  • 1
    Neither the question text, nor the code the question asker provided includes jQuery. If you're hellbent on suggestion a jQuery solution, it might be good to at least caveat it with the instruction they will need to add jQuery to their project. – dgeare Jul 24 '18 at 15:47
-1

here is your example

<!DOCTYPE HTML>
<html>
<head>
  <meta charset="utf-8">

  <script>
    function countRabbits() {
      for(var i=1; i<=3; i++) {
        alert("Rabbit number " + i);
      }
      return false;
    }
  </script>
</head>
<body>
  <input type="button" onclick="countRabbits()" value="Count rabbits"/>
</body>
</html>

First of all, take care about closed pair tags. In your snippet you have unclosed script tag. Don't use button where it isn't necessary, but use the input type button instead.