Return In Javascript

2011-07-30

The keyword return in javascript plays an important role in javascript execution of code. If false is returned from a function, then normal execution is stopped.

For example look at the html code


<asp:Button ID="btnTruncate" runat="server" Text="Truncate" OnClick="btnTruncate_Click"
OnClientClick="return DisplayNotificationMessage();" />




function DisplayNotificationMessage()

{

try

{

var selectedCaheComponents = new String("")

var gridView = document.getElementById("grdTruncateCache")



for (var rowIndex = 1; rowIndex <= 6; rowIndex++)

{

var rowElement = gridView.rows[rowIndex];

var chkBoxElement = document.getElementById("grdTruncateCache_ChkSelect_" + (rowIndex - 1))

if (chkBoxElement.checked)

{

var elem = document.getElementById("grdTruncateCache_lblCache_" + (rowIndex - 1));

selectedCaheComponents = selectedCaheComponents + "n"

if (elem.innerText != undefined)

{

selectedCaheComponents = selectedCaheComponents + elem.innerText

}

else

{

selectedCaheComponents = selectedCaheComponents + elem.textContent

}



}

}



if (selectedCaheComponents.length > 0)

{

selectedCaheComponents = selectedCaheComponents + "n" + "?"

var answer = confirm("Please note that this is an irreversible operation as you are going to truncate the following Cache Components. n" + selectedCaheComponents)

if (answer)

{

return true;

}

else

{

return false;

}



}

return false;

}

catch (err)

{

return false;

}

}

</script>






If false is returned from this function then no postback event of button occurs. It occurs only when the true is returned from the function

Works in following

0 comments: