skip to Main Content

None of the “Similar quiestons” helped me

I have a button that I need to disable once it was clicked:

<button class="button" type="submit" id="saveButton" hidden="hidden" style="display:none">submit</button>
<input onclick="validator()" id="handleSaveButton" class="button" type="button" value="my button value">

Here’s how I do it:

function validator(){
    $(".buttons :input[value:'my button value']").prop("disabled",true)
    ...
    //something else goes here
    ...
    document.getElementById("saveButton").click();
}

Now this works but my page also has required fields. And if those aren’t filled, you have to refresh the whole page to make save button available again.

I’m looking for a solution to

  • Make my button disabled once clicked
  • Make it enabled again if required fields are not filled

Thanks. Please note that I cannot change the structure with hidden submit and actual button

2

Answers


  1. Chosen as BEST ANSWER

    Somebody posted an answer but it got deleted unfortunately. Here's their solution:

    var requiredFields = document.querySelectorAll("[required]");
    var allFilled = true;
    requiredFields.forEach(function(field) {
        if (field.value.trim() === '') {
            allFilled = false;
            return false; // to break out of the forEach loop
        }
    });
    
    if (allFilled) {
        $(".buttons :input[value:'my button value']").prop("disabled", true);
        document.getElementById("saveButton").click();
    }
    

    Worked great for me


  2. There is no need of complicated selector inside JQuery. Just differ elements by className: .buttons.handler And .buttons.save.

    <button class="buttons save" type="submit" id="saveButton" style="display:none"> submit </button>
    <input onclick="validator()" id="handleSaveButton" class="buttons handler" type="button" value="my button value"/>
    

    After that, you can write this simple JS code. And don’t forget, jQuery always return a collection of objects with a length. That’s why i used $()[0] to handle the first element.

    function validator(){
        const btnHandler = $(".buttons.handler")[0];
        $(btnHandler).attr('disabled',true);
          //
    
        const btnSave = $(".buttons.save")[0];
        $(btnSave).css({ display: "block" });
        btnSave.click();
      }
    

    Please Don’t forget to mark as solved

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search