Niranjan Godbole Niranjan Godbole - 4 years ago 95
jQuery Question

Jquery not returning false and continue executing the rest of the code

net application with jquery. I have one button and gridview with checkbox. If none of the checkboxes are checked i dont want to button to fire and go to server side. I am trying as below.

This is my button.

<asp:Button ID="btnRegretletter" runat="server" Text="Send Regret Letter" class="submitLink blueButton" OnClientClick="javascript:check()" OnClick="btnRegretletter_Click" ValidationGroup="VGsubmit" />


This is my jquery code.

function check() {
alert("I have been called");
var valid = false;
var ResultArrayFirst = [];
$('#<%= gdvRegretletter.ClientID %> input[type="hidden"]').each(function () {
if ($(this).closest('tr').find('input[type="checkbox"]').is(':checked'))
{
ResultArrayFirst.push($(this).val());
}
});
alert(ResultArrayFirst);
if (ResultArrayFirst.length > 0) {
valid = true;
}
else
{
alert("Please select at least one vendor to send Regret Letter.");
valid = false;
return valid;
}
}


In the above code whenever i dont select any checkboxes from gridview my variable will be null and my else part should execute. I am able to fire alert but as soon as my alert fires and clicks on ok my page refreshes and it will got to server side. May I know how can i prevent? Any help would be appreciated. Thank you.

Answer Source

return valid; should be outside else part like following snippet, because in your case if length would be greater than 0 function will not return.

if (ResultArrayFirst.length > 0) {
   valid = true;
}
else
{
    alert("Please select at least one vendor to send Regret Letter.");
    valid = false;
}
return valid;

Plus you need to check it like this :

OnClientClick="return check()"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download