I’m working on asp.net core razor pages and I'm trying to disable all the buttons on the page when a button clicked my code looks somthing 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:
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);
});
})
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;
}