skip to Main Content

I have a form that have a button inside. That Button shall not submit the form. It shall trigger a JS-Funktion.

The Button:

$(document).ready(function () {

  $('.onlynumbers').keypress(function (e) {
    var charCode = (e.which) ? e.which : event.keyCode    
    if (String.fromCharCode(charCode).match(/[^0-9]/g))    
      return false;
  }); 

  $("#weiter").click(function(event) {
   if(parseInt("#wortanzahl".value) > 0){
      $("#wk").attr("disabled", false);
      alert ("Test");
    } 
    event.preventDefault();
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  ...
  <button class="btn btn-success mt-3" id="weiter">Aktualisieren</button>
  ...
</form>

When I cklick on the Button. Nothing happend. What can it be?

3

Answers


  1. The if condition inside your click handler will never evaluate to true. Remove it and your alert will work.

    $(document).ready(function () {
    
      $('.onlynumbers').keypress(function (e) {
        var charCode = (e.which) ? e.which : event.keyCode    
        if (String.fromCharCode(charCode).match(/[^0-9]/g))    
          return false;
      }); 
    
      $("#weiter").click(function(event) {
          $("#wk").attr("disabled", false);
          alert ("Test");
        event.preventDefault();
      })
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <form>
      ...
      <button class="btn btn-success mt-3" id="weiter">Aktualisieren</button>
      ...
    </form>
    Login or Signup to reply.
  2. Any buttons in a form do a submit by default,
    you just have to change

     <button class="btn btn-success mt-3" id="weiter">Aktualisieren</button>
    

    by

     <button type="button" class="btn btn-success mt-3" id="weiter">Aktualisieren</button>
    
    Login or Signup to reply.
  3. Here is likely what you want based on the incomplete information you have given:

    $(document).ready(() => {
      $("#wortenForm").on("submit", (event) => {
          event.preventDefault(); // stop submission
          const val = parseInt($("#wortanzahl").val());
          $("#wk").attr("disabled", val < 0); // no need to use an if on a boolean
          alert("Test");
      })
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <form id="wortenForm">
      <input type="number" class="onlynumbers" />
      <input type="number" id="wortanzahl" />
      <button id="wk" disabled>WK</button>
      <button type="submit " class="btn btn-success mt-3 " id="weiter ">Aktualisieren</button>
      ...
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search