Reputation: 5539
I am trying to validate fields on button click using Jquery but the problem is that it seems that code behind event and jquery event are running in parallel.
(UPDATED)
<asp:Button ID="btnsave" runat="server" ClientIDMode="Static" OnClientClick="return clientFunction()" CssClass="ButtonText"
Text="SAVE" OnClick="btnsave_Click" />
CLIENT SIDE VALIDATION:
<script type="text/javascript">
function clientFunction() {
var isValid = true;
$('#txtsupplieruserid,#txtsuppliername,#txtbusinessemailid,#txtorganizationname,#txtphonenumber,#txtcity,#txtstate,#txtpostalcode,#txtaddress').each(function () {
if ($.trim($(this).val()) == '') {
isValid = false;
$(this).css({
"border": "1px solid red",
"background": "#FFCECE"
});
}
else {
$(this).css({
"border": "",
"background": ""
});
}
});
if (isValid == false) {
e.preventDefault();
return isValid;
}
else {
return isValid;
}
}
</script>
I would like to validate through Jquery first than go to code behind if it passes clientside validation. I want to do this using Jquery and not pure Javascript.
Upvotes: 3
Views: 8063
Reputation: 14604
You can use OnClientClick
for client side validation and if validation passes return true
otherwise return false
. If true is returned server side function will be called otherwise it won't.
<asp:Button ID="btnsave" runat="server" ClientIDMode="Static" CssClass="ButtonText" Text="SAVE" OnClientClick="return clientFunction()" onclick="btnsave_Click" />
function clientFunction()
{
var isValid = true;
$('#txtsupplieruserid,#txtsuppliername,#txtbusinessemailid,#txtorganizationname,#txtphonenumber,#txtcity,#txtstate,#txtpostalcode,#txtaddress').each(function ()
{
if ($.trim($(this).val()) == '') {
isValid = false;
$(this).css({
"border": "1px solid red",
"background": "#FFCECE"
});
}
else {
$(this).css({
"border": "",
"background": ""
});
}
});
if (isValid == false) {
return false;
}
else {
return true;
}
}
If your controls are server controls
than you may need to use ClientIDMode="Static"
. So their ID remains same.
Upvotes: 1