I have this java script validation function that fires when the client clicks btnsave if the text of the text box is empty then a message box is displayed and the focus is on the text box but i cannot seem to prevent the page from posting back when the validation fails AM I missing something. here is my code
function validate()
{
var itemscanned;
itemscanned = document.getElementById('txtItemCode');
if (itemscanned.value == '')
{
alert("Plz Enter Item Code");
return false;
itemscanned.focus
}
else
{
alert(itemscanned.value);
}
}
I have this java script validation function that fires when the client clicks btnsave if the text of the text box is empty then a message box is displayed and the focus is on the text box but i cannot seem to prevent the page from posting back when the validation fails AM I missing something. here is my code
function validate()
{
var itemscanned;
itemscanned = document.getElementById('txtItemCode');
if (itemscanned.value == '')
{
alert("Plz Enter Item Code");
return false;
itemscanned.focus
}
else
{
alert(itemscanned.value);
}
}
Share
Improve this question
edited Dec 28, 2012 at 13:24
Ignacio Correia
3,6688 gold badges40 silver badges68 bronze badges
asked Dec 28, 2012 at 13:17
nayef harbnayef harb
7531 gold badge10 silver badges19 bronze badges
1
-
Is this the
submit
button for the form? – Mike Perrenoud Commented Dec 28, 2012 at 13:25
4 Answers
Reset to default 5Write return before function name like this
<asp:Button ID="btnSave" runat="server" Text="Save" CssClass="buttons" OnClientClick="return validate()"/>
If this is an ASP.NET WebForms application, you really should consider using the Validator controls. They handle all of client-side logic you are asking for.
If you are using MVC, there is also a way to do model validation on the client side.
add this if its asp button control
OnClientClick = "return validate();"
if it is html button add this
onclick = "return validate();"
Ît belongs how you handle the events. Please show the asp markup and the binding of the javascript event.
You can try to stop event propagation using javascript:
event.stopPropagation();
Read about it here: https://developer.mozilla/en-US/docs/DOM/event.stopPropagation
Note: you have to get the event as an parameter to the validate function:
function validate(event) {
var itemscanned;
itemscanned = document.getElementById('txtItemCode');
if (itemscanned.value == '') {
alert("Plz Enter Item Code");
event.stopPropagation();
itemscanned.focus
return false;
}
else
{
alert(itemscanned.value);
}
}
Hope this helps. It's very important how you bind the validate function the button, because asp generates a lot of javascript on its own (google for asp client validation).