I have a ASP.NET page using ValidationGroup. If the validation fails, I want the page to scroll to an anchor (#edit). Here is my code so far:
<div id="edit">This is my anchor area</div>
<div>
<asp:TextBox runat="server" ID="txtDescription" ValidationGroup="Edit" />
<asp:TextBox runat="server" ID="txtComment" ValidationGroup="Edit" />
<asp:Button runat="server" ID="btnSave" OnClick="btnSave_OnClick" OnClientClick="ValidatePage();" ValidationGroup="Edit" CausesValidation="True" />
</div>
<script type="text/javascript">
function ValidatePage() {
if (!Page_ClientValidate("Edit")) {
location.hash = "edit";
}
}
</script>
First time I click the button, the page scroll to the anchor (#edit) if validation fails. But, If I click the button again, the page does not scroll to the anchor.
How can this be fixed, so that the page allways scroll to the anchor if validation fails? Even if the button is allready clicked (#edit is in the url).
CodePudding user response:
const anchor = "anchor-id";
window.location.hash = anchor;
setTimeout(() => {
window.location.hash = "";
setTimeout(() => {
window.location.hash = anchor;
}, 50);
}, 50);
This code will first set the location.hash to the specified anchor, then wait for 50 milliseconds, set the location.hash to an empty string, wait for another 50 milliseconds, and finally set the location.hash back to the anchor. This will cause the page to scroll to the anchor twice.
You can adjust the setTimeout delay values based on your specific requirements. Keep in mind that this approach is not the most efficient and may not work in all cases. You may want to consider using a different method, such as using JavaScript to directly manipulate the page elements and scroll to the anchor, or using a library or plugin that is specifically designed to handle scrolling to anchors.