Hi @AKM Azad,
How can I complete both task?
First prevent the enter key from submitting the form.
Secondly, you set the EnterPressFocusChange
event for both the DropDownList and TextBox elements. Then you need to determine the event source element and perform the corresponding operation.
Third, since the OnClientClick event is executed before OnClick event, you can return true/false to determine whether to allow the form to be submitted. Therefore, you do not need to set the UseSubmitBehavior
property in submit button.
Here is a simple test:
<head runat="server">
<title></title>
<script src="Scripts/jquery-3.4.1.min.js" ></script>
<script type="text/javascript">
//prevent submit from Enter key
$(document).ready(function () {
$(window).keydown(function (event) {
if (event.keyCode == 13) {
event.preventDefault();
return false;
}
});
});
function CheckInputData() {
// If valid input return true
// else return false
// As a simple example, determine whether the TextBox value contains "test"
var text = document.getElementById("tb1").value;
if (text.includes("test")) {
console.log("Valid Input");
return true;
} else {
console.log("Invalid Input");
return false;
}
}
function EnterPressFocusChange(event) {
if (event.key === "Enter" || event.keyCode === 13) {
// Determine which element is the source of the event
if (event.target.id === "DropDownList1") {
// Do something here, print its value on the console as an example
const dropdown = document.getElementById("DropDownList1");
const selectedOption = dropdown.options[dropdown.selectedIndex].text;
console.log("Dropdown selected: " + selectedOption);
// change focus here, move focus from dropdownlist to textbox
document.getElementById("tb1").focus();
} else if (event.target.id === "tb1") {
// Do something here, print its value on the console as an example
const textboxValue = event.target.value;
console.log("Textbox input: " + textboxValue);
// change focus here, move focus from textbox to button
document.getElementById("btnButton").focus();
}
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server" onkeyup="EnterPressFocusChange(event)" AutoPostBack="true">
<asp:ListItem Value="1" Text="Item1">Item1</asp:ListItem>
<asp:ListItem Value="2" Text="Item2">Item2</asp:ListItem>
<asp:ListItem Value="3" Text="Item3">Item3</asp:ListItem>
</asp:DropDownList>
<br />
<asp:TextBox ID="tb1" Text="0" runat="server" onkeyup="EnterPressFocusChange(event)"></asp:TextBox><br />
<asp:Button ID="btnButton" runat="server" Text="Button" OnClientClick="return CheckInputData(this);" OnClick="btnButton_Click"/>
</div>
</form>
</body>
Result:
Best regards,
Xudong Peng
If the answer is the right solution, please click "Accept Answer" and kindly upvote. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.