Returning Values in javascript function - javascript

I have a scenario where there are 4 text boxes and one Radio Button list. If i click the Submit button by leaving all fields it should alert me . I used 4 Required Validator s for text boxes and a java script function for the radio button list.
My mark up language and function is:
function Validate() {
var radio = document.getElementsByName("rdbGender");
for (var i = 0; i < radio.length; i++) {
if (radio[i].checked) {
return true;
}
else
{
alert("Choose a Gender");
return false;
}
}
}
Aspx page is:
<asp:Button ID="btnSave" Text="Save" runat="server" Width="50px" OnClientClick= "Validate()"
OnClick="btnSave_Click" />
When ever i click the button by leaving fiealds empty, and leaving radio button list with out selecting a item, it is alerting but if i press ok it is executing further. I read in one website that if we write " return true " after alert has been showed and clicking ok it will execute further,,but i wrote "return false" after alert it means untill i check one radio button it should not execute...Where am i wrong??
Javascript:
<script type="text/javascript">
function Validate() {
var checkedVal = false;
var radio = document.getElementsByName("rdbGender");
for (var i = 0; i < radio.length; i++) {
if (radio[i].checked) {
checkedVal = true;
return checkedVal;
}
else {
alert('Chhooose gender');
return checkedVal;
}
}
}
</script>
Mark up design:
<tr>
<td>
Gender
</td>
<td>
<asp:RadioButtonList ID="rdbGender" RepeatDirection="Horizontal" runat="server">
<asp:ListItem Value="MALE">
</asp:ListItem>
<asp:ListItem Value="FEMALE">
Female
</asp:ListItem>
</asp:RadioButtonList>
</td>
</tr>
.
.
.
.![enter image description here][2]
<td>
<asp:Button ID="btnSave" Text="Save" runat="server" Width="50px" ValidationGroup="Star" OnClientClick="return Validate()"
OnClick="btnSave_Click" />
</td>

Try using return when calling client function.
<asp:Button ID="btnSave" Text="Save" runat="server" Width="50px"
OnClientClick= "return Validate();"
OnClick="btnSave_Click" />
For first iteration of for, If first radio button is not checked it would go to else part which is showing alert and returning false. Please implement below code.
function Validate() {
var checkedval=false;
var radio = document.getElementsByName("rdbGender");
for (var i = 0; i < radio.length; i++) {
if (radio[i].checked) {
checkedval=true;
return checkedval;
}
}
return checkedval;
}

A function can only have one return value. When return true is executed, the function immediately return true and stop going further. Therefore, comment out the return true and try.
function Validate() {
var radio = document.getElementsByName("rdbGender");
for (var i = 0; i < radio.length; i++) {
if (radio[i].checked) {
//return true;
//this return true causes the problem.
}
else
{
alert("Choose a Gender");
return false;
}
}
}

Related

How to ensure the selected file count to be either zero or one using javascript

In my application I have edit button in gridview where user will click edit button and when he clicks edit button
all the data related to that particular edited row gets binded to corresponding textboxes and fileupload controls
at this case user may select another file or he may not select another file if selected the count of the files should not be
greater than one or zero how can i do this
Below is my fileupload contol,update button and edit image code
<asp:FileUpload ID="filuploadmp3" runat="server" Width="224px" multiple="multiple" onchange="javascript:return checkwavextension();" />
<asp:Button ID="btnupdate" runat="server" OnClick="btnupdate_Click" Text="Update" Width="62px" OnClientClick="return validateStuff();" />
<asp:ImageButton ID="Btn1" runat="server" Text="Edit" CommandName="mybutton" Width="20px" ImageUrl="~/images/page_white_edit.png" ToolTip="Edit" />
To allow only one file to select then remove multiple="multiple" from FileUpload
<asp:FileUpload ID="filuploadmp3" runat="server" Width="224px" onchange="javascript:return checkwavextension();" />
Or if you want to have this then you can check count like
function ValidateFile(){
var fileCount = document.getElementById('filuploadmp3').files.length;
if(fileCount > 1) // Selected images with in 1count
{
alert("Please select only 1!!");
return false;
}
else if(fileCount <= 0) // Selected atleast 1
{
alert("Please select atleat 1!!");
return false;
}
return true; // Good to go
}
function checkwavextension() {
var chkFile = document.getElementById('<%= filuploadmp3.ClientID %>');
var label = document.getElementById('<%= lblerrmsg.ClientID%>');
var myfile = chkFile.value;
if (myfile.indexOf(".wav") > 0 || myfile.indexOf(".mp3") > 0) {
label.innerText = "Valid Format";
//check mode insert or update
//if update then
return ValidateFile();
} else {
label.innerText = "Invalid Format";
chkFile.value = "";
}
}
function ValidateFile(){
var fileCount = document.getElementById('filuploadmp3').files.length;
if(fileCount > 1) // Selected images with in 1count
{
alert("Please select only 1!!");
return false;
}
else if(fileCount <= 0) // Selected atleast 1
{
alert("Please select atleat 1!!");
return false;
}
return true; // Good to go
}

OnClientClick causes webpage refresh

I have an ASP.NET button on a webpage:
<asp:Button ID="TickButton" runat="server" OnClientClick="SelectSome()" Text="Tick" />
and a JavaScript function:
function SelectSome() {
var id = document.getElementById("ctl00_ContentPlaceHolder1_txtSelectSome").value;
if (isNaN(id)==false)
{
var frm = document.forms[0], j = 0;
for (i = 0; i < frm.elements.length; i++) {
if (frm.elements[i].type == "checkbox" && j < id) {
frm.elements[i].checked = true;
j++;
}
}
}
else
{
alert("You must enter a number.")
}
return false;
}
When I click on the button; the JavaScript function runs and then the webpage refreshes. Why does the webpage refresh? According to this link; returning FALSE should stop the webpage from refreshing: Stop page reload of an ASP.NET button
Use return for clientclick.
<asp:Button ID="TickButton" runat="server" OnClientClick="return SelectSome()" Text="Tick" />
OR
you can simply use html button of server side coding is not required then.
<asp:Button Text="Tick" runat="server" OnClientClick="return SelectSome()" />

header checkbox not working first click

hey everyone i have two view
1- Index
2- Edit
i have a grid its header have one checkbox i want to click checkbox all rows checkbox is checkbox. in my header checkbox its not working first time when i click uncheck then check its work fine. i dont know why and what is the problem in my code please help
here is my index view its have Script
function Check_Uncheck() {
$('#SelectAll').click(function () {
if (this.checked) {
$('.checkbox:enabled').each(function () {
this.checked = true;
});
}
else {
$('.checkbox:enabled').each(function () {
this.checked = false;
});
}
});
}
and here is my Edit its have checkbox
<input type="checkbox" id="SelectAll" onclick="Check_Uncheck();" tabindex="3" />
If you want to select and unselect all checkboxes of the gridview row, then you can do something like below:-
<script type="text/javascript">
function SelectAll(obj) {
var valid = false;
var chkselectcount = 0;
var gridview = document.getElementById('<%= GridView1.ClientID %>');
for (var i = 0; i < gridview.getElementsByTagName("input").length; i++) {
var node = gridview.getElementsByTagName("input")[i];
if (node != null && node.type == "checkbox") {
node.checked = obj;
}
}
return false;
}
</script>
Gridview aspx:-
<asp:GridView ID="GridView1"
runat="server" AutoGenerateColumns="false"></asp:GridView>
And onButton click
Select :
<asp:LinkButton ID="lnkdelete" runat="server" CausesValidation="false" Text="All" OnClientClick="SelectAll(true); return false"></asp:LinkButton>
|
<asp:LinkButton ID="lnkundelete" runat="server" CausesValidation="false" Text="None" OnClientClick="SelectAll(false); return false"></asp:LinkButton>

Checking if radiobuttonlist has been selected

I'm using this code to check if a radiobuttonlist has been selected, however it doesn't return false if nothing has been checked, and continues through to the function in the class behind. The radiobutton list is generated from databinding in codebehind.
<asp:LinkButton class="btn" id="linkDelete" runat="server" onclick="link_Delete" OnClientClick="checkform()">Delete Template</asp:LinkButton>
<asp:radiobuttonlist id="optMessageType" runat="server" onselectedindexchanged="optMessageType_SelectedIndexChanged" RepeatDirection="Vertical" CssClass="none-table">
</asp:radiobuttonlist>
function checkform() {
var radiolist = document.getElementById('<%= optMessageType.ClientID %>');
var radio = radiolist.getElementsByTagName("input");
if (radio.length > 0) {
for (var x = 0; x < radio.length; x++) {
if (radio[x].type === "radio" && radio[x].checked) {
//alert("Checking...");
// alert("Selected item Value " + radio[x].value);
var r = confirm("Are you sure you want to delete this template?")
if (r == true) {
//alert("You pressed OK!")
return true;
}
else {
//alert("You pressed Cancel!");
return;
}
}
else {
alert("Select a template to delete");
return;
}
}
}
else {
alert("nope");
return;
}
}
Code Behind:
protected void link_Delete(object sender, System.EventArgs e)
{
Label3.Text = "Deleted!"; //For Testing
}
You should write
<asp:LinkButton class="btn" id="linkDelete" runat="server" onclick="link_Delete" OnClientClick="return checkform();">Delete Template</asp:LinkButton>
i have added return in OnClientClick atribute funcion call
hope this may solve our problem.

Cancel ajax modalpopupextender using javascript

I have a modalpopupextender with a targetcontrolid = buttCopyFormula. The buttCopyFormula is wrapped in a span tag for the user to verify they want to proceed. The button also has a javascript function that verifies there is text in one of the fields and if there is places it in a textbox within the modalpopup.
If there isn't text in the field I want to cancel the popup and display a message.
I've had the span around the button for a while, but am just adding the verification function. I would imagine there is a better way to do this, but just not sure what it is.
What is the best way to execute this functionality?
TargetControl Button
<span onclick="return confirm('Copy the selected formula?')">
<asp:ImageButton ID="buttCopyFormula" ImageAlign="AbsBottom" OnClientClick="transferName()" runat="server" ImageUrl="~/images2020/copy_32.png" />
<b style="color:White">Copy</b>
</span>
Modal Popup
<asp:ModalPopupExtender ID="ModalPopupExtender2" Y="20" runat="server"
BackgroundCssClass="modalBackground" CancelControlID="buttFormulaCancel"
PopupControlID="Panel2" TargetControlID="buttCopyFormula">
</asp:ModalPopupExtender>
<asp:Panel ID="Panel2" runat="server" CssClass="modalQuestionBackground"
Style="display:none"><br />
<h5>Enter a Name for the Formula</h5>
<br /><br />
Formula Name:
<asp:TextBox ID="txtFormulaNameNew" CssClass="controltext" Width="65%" runat="server" Text=""></asp:TextBox><br /><br />
<center>
<asp:Button ID="buttFormulaSaveNew" runat="server" CssClass="button"
OnClick="buttFormulaSaveNew_Click" Text="Save Formula" />
<asp:Button ID="buttFormulaCancel" runat="server" CssClass="button"
Text="Cancel" />
</center>
<br />
</asp:Panel>
JavaScript Function
function transferName() {
var v = document.getElementById("ctl00_ContentPlaceHolder1_txtFormulaNameNew").value;
var f = document.getElementById("ctl00_ContentPlaceHolder1_txtFormulaName");
if (v === "") {
alert("Please select the formula you want to copy before proceeding");
return false;
}
f.value = v
}
I've been working on this and first removed the span around the button, put a fake hyperlink for the modal popup and added a behavior id to the popup. I have also changed the javascript as follows...
New Javascript
function transferName() {
var v = document.getElementById("ctl00_ContentPlaceHolder1_txtFormulaNameNew").value;
var f = document.getElementById("ctl00_ContentPlaceHolder1_txtFormulaName");
if (f === "") {
alert("Please select the formula you want to copy before proceeding");
return false;
} else {
if (confirm('Copy selected formula?')) {
f.value = v;
var mod = $find("ModalPopupExtender2");
alert(mod.id.toString);
mod.show;
return false;}
}
}
I still can't get the modalpopup to show. I imagine it's because it's wrapped in an update panel. Any ideas??
You may subscribe to showing event of ModelPopupExtender and cancel showing dependent on some conditions. Put script below at page AFTER THE ScriptManager control
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoadedHandler);
function pageLoadedHandler(sender, args){
var popupExtender = $find("ModalPopupExtender2"); // BehaviorId of popup extender
popupExtender.remove_showing(onPopupShowing);
popupExtender.add_showing(onPopupShowing);
}
function onPopupShowing(sender, args) {
var txtFormulaNameNew;
var txtFormulaName = $get("<%= txtFormulaName.ClientID %>");
if (formulaTextBox.value.length === 0) {
alert("Please select the formula you want to copy before proceeding");
args.set_cancel(true);
} else {
if (confirm('Copy selected formula?')) {
txtFormulaNameNew = $get("<%= txtFormulaNameNew.ClientID %>");
txtFormulaNameNew.value = txtFormulaName.value;
}
}
}

Categories

Resources