For clearing textboxes, it is recommended to handle it on the client side (edit: as suggested by MightyLampshade you can find one of 1000 examples here), as there is no need for a server round-trip. If you have a clear button:
$("#clear").click(function() {
$(".can-be-cleared").val("");
});
It should be noted that this will clear all elements with the class name can-be-cleared
(assuming you may not want to clear each input individually but a specific set; if this is not the case, replace it with input[type=text]
) when you click on an element with the id clear
.
If each "clear" button needs to clear a specific textbox, then you will have to repeat them because when you click the button, the textbox will lose focus. Alternatively, you could remember the last focused textbox. Let's explore both options:
<input type="text" id="textbox1"/>
<button class="clear-button" data-textbox="textbox1">clear</button>
The JavaScript code for this would be:
$(".clear-button").click(function() {
$("#"+$(this).data("textbox")).val("");
});
A simpler alternative (preferable if there are no other specific requirements) could involve keeping track of the last focused textbox:
var lastFocused = undefined;
$("input[type=text]").focus(function () {
lastFocused = $(this);
});
$("#clear-field").click(function () {
if (lastFocused !== undefined) {
lastFocused.val("");
}
});
Ensure that the ID used for your clear button matches with $("#clear-field")
, assuming in this scenario:
<button id="clear-field">Clear</button>
If server-side processing is necessary (for any other reason), the TextBox
that generated the event can be accessed through the sender
parameter:
Dim textbox As TextBox = DirectCast(sender, TextBox)
textbox.Text = String.Empty