Home > database >  Call JS function on click of a button in a Bootstrap modal
Call JS function on click of a button in a Bootstrap modal

Time:12-14

I have a bootstrap modal, where I have few buttons to capture feedback.

I want to call a JS function on click of one of the buttons.

However, on click of the button, the modal just closes without calling the JS Function.

But, if I do the same onclick event on any other element not in the modal, it works fine.

js

<script>
          
   function sayHello() {
        alert("Demo Alert")
   }
</script>

HTML

<div

id="exampleModal"
tabindex="-1"
role="dialog"
aria-labelledby="exampleModalLabel"
aria-hidden="true"
>
<div
  
  role="document"
>
  <div >
    <div >
      <div >
        <div >
          <div >
            <h3 >How was the Session?</h3>
            <form action="#" id="mood-tracker">
              <div >
                  <div >
                    <button type="submit" value="Good" onclick="sayHello()">
                      <i
                        
                       
                      ></i
                      >Good
                    </button>
                  </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
</div>

Where am I going wrong?

CodePudding user response:

Please do not use button type "submit". Use type "button" instead of like this:

<button type="button" value="Good" onclick="sayHello()"><i ></i>Good </button>

CodePudding user response:

C must be capitle

use onClick not onclick

<button type="button" onClick="sayHello()">Button</button>

CodePudding user response:

I think you should use window.confirm() instead of window.alert().

HTML

<button type="submit" value="Good" onclick="sayHello()">

JS

function sayHello() {
   return confirm('Demo Alert');
}

I found this answer on another Stack Overflow page : HTML - How to do a Confirmation popup to a Submit button and then send the request?

CodePudding user response:

try this:

JS

function sayHello(e) {
    e.preventDefault();
    alert("Demo Alert");
    // If you want this modal to close after handling your logic
    $('#exampleModal').modal('hide'); 
}

HTML

<button type="submit" value="Good" onclick="sayHello">
  • Related