Home > front end >  ASP.NET Core Razor Pages - Disable all the buttons on multiple forms
ASP.NET Core Razor Pages - Disable all the buttons on multiple forms

Time:08-25

I’m working on ASP.NET Core Razor Pages and I'm trying to disable all the buttons on the page when a button is clicked. My code looks something like this:

<form method="post" onsubmit="DisableBtns()">
<button  type="submit" name="btn1" > </button>
</form>


<form method="post" onsubmit="DisableBtns()">
<button  type="submit" name="btn2" > </button>
</form>


<script>
    function DisableBtns() {
        alert("The form was submitted");
        btn1.disabled = true; btn2.disabled = true; return true;
    }
</script>

My problem is the alert did execute but the buttons are not disabled.

The following code does work but I don't want it I want to use the function way:

<form method="post" onsubmit="btn1.disabled = true; btn2.disabled = true; return true;">
</form>

Can someone please help me resolve this issue or if you have a better way that works on Razor Pages I would really appreciate it.

CodePudding user response:

Unsure whether you have declare btn1 and btn2 variables as you didn't show them.

Solution 1: With JavaScript .querySelectorAll()

function DisableBtns() {
    alert("The form was submitted");

    document.querySelectorAll("form button").forEach(x => {
        x.disabled = true;
    });
        
    return true;
}

Solution 2: With jQuery

Pre-requisite:

You have imported jQuery library.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
function DisableBtns() {
    alert("The form was submitted");
    
    $("form button").prop('disabled', true);
        
    return true;
}

CodePudding user response:

You can try to remove onsubmit and use $("form button[type='submit']").click(),here is a demo:

form:

<form method="post">
    <button  type="submit" name="btn1"> </button>
</form>


<form method="post">
    <button  type="submit" name="btn2"> </button>
</form>

js:

$("form button[type='submit']").click(function(event) {
            event.preventDefault();
            $("form button[type='submit']").each(function(index) {
                $(this).attr("disabled",true);
            });
        })
  • Related