Evaluation of RadioButtonList control using JavaScript - ASP.Net - javascript

I am developing a website using asp.net and C#.
I am using a RadioButtonList control. The code snippet for RadioButtonList is shown below
<asp:RadioButtonList ID="RLCompareParameter" runat="server"
RepeatDirection="Horizontal" meta:resourcekey="rsKey_RLCompareParameter"
AutoPostBack="True"
onselectedindexchanged="RLCompareParameter_SelectedIndexChanged">
<asp:ListItem Selected="True" Value="Forms" meta:resourcekey="rsKey_RLCompareParameterListItemForms" Text="Forms"></asp:ListItem>
<asp:ListItem Value="Segments" meta:resourcekey="rsKey_RLCompareParameterListItemSegments" Text="Segments"></asp:ListItem>
<asp:ListItem Value="Questions" meta:resourcekey="rsKey_RLCompareParameterListItemQuestions" Text="Questions"></asp:ListItem>
</asp:RadioButtonList>
There is a button in the same page. While clicking on that button i want to display an alert message based on the selected radio list item using javascript. Some part of my javascript function is shown below
var RLCompareParameter = this.document.getElementById("<%= RLCompareParameter.ClientID %>");
if (RLCompareParameter.SelectedValue == "Forms") {
if (document.getElementById("<%= lbAvailableForms.ClientID %>").value == "") {
alert("Please select a form from Available Evaluation Forms ");
return false;
}
} else if (RLCompareParameter.SelectedValue == "Segments") {
if (document.getElementById("<%= lbAvailableSegments.ClientID %>").value == "") {
alert("Please select a segment from the available segments ");
return false;
}
} else if (RLCompareParameter.SelectedValue == "Questions") {
if (document.getElementById("<%= lbAvailableQuestions.ClientID %>").value == "") {
alert("Please select a Question from the available questions");
return false;
}
}
But the if(RLCompareParameter.SelectedValue == "some value") always false. i think there is no attribute like selected value for RadioButtonList control. I hope someone help me

In html, there is no such thing as a RadioButtonList. Your RLCompareParameter variable will be a reference to the table or span that is containing the three input elements (thats what the ASP.NET control outputs into your page). SelectedValue is only for ASP.NET code, not javascript.
You will have to get a reference to the specific input element itself and look at its checked property in your if statements to see whether that radio button is selected or not. There are several ways to do this. Here's one that might work:
var RLCompareParameter = document.getElementById("<%= RLCompareParameter.ClientID %>");
var radioButtons = RLCompareParameter.getElementsByTagName('input');
if (radioButtons[0].checked) {
if (document.getElementById("<%= lbAvailableForms.ClientID %>").value == "") {
alert("Please select a form from Available Evaluation Forms ");
return false;
}
} else if (radioButtons[1].checked) {
if (document.getElementById("<%= lbAvailableSegments.ClientID %>").value == "") {
alert("Please select a segment from the available segments ");
return false;
}
} else if (radioButtons[2].checked) {
if (document.getElementById("<%= lbAvailableQuestions.ClientID %>").value == "") {
alert("Please select a Question from the available questions");
return false;
}
}

Related

Form validation for Empty checking is not working properly In asp.net

I want to validate my form to avoid Empty. I am using asp.net inbuilt controls on my page i am using loop to check all fields are fill or not but its always showing empty even-though after filled all field. Is there any another approach to achieve same.
I have design my page in such way that its post back after selection of drop down list. that's why its not working i don't know.
<body>
<form id="form1" runat="server">
<div id="DivMainWindow" class="mainHeaderOuter">
<%--Inside this Div my all ASP controls are present--%>
<asp:ListBox ID="ddlregion" runat="server"
<asp:ListItem Value="0">Select</asp:ListItem>
</asp:ListBox>
<dx:ASPxDateEdit ID="deOrderDate" runat="server" Width="220px" AllowUserInput="false" Height="25px"EditFormatString="dd-MMM-yyyy" DisplayFormatString="dd-MMM-yyyy" EditFormat="Custom"ClientInstanceName="deOrderDate" OnInit="deOrderDate_Init">
..............
<asp:Button ID="btnGenerate" OnClientClick="return validate();" runat="server" OnClick="btnGenerate_Click" Text="Generate" />
so on
JAva script :
<script>
function validate() {
var inputTags = document.getElementsByTagName("input");
for (i = 0; i < inputTags.length; i++) {
if (inputTags[i].value === "") {
alert("All fields are required");
return false;
}
}
return true;
}
while inspecting on browser i am getting this :
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="">
I also tried individual control to check its empty or not but its not looping in such a way :
var Region = document.getElementById('<%=ddlregion.ClientID %>').value;
var Depot = document.getElementById('<%=ddlDepot.ClientID %>').value;
var INQFileType = document.getElementById('<%=ddlInqfileType.ClientID %>').value;
var QUOFileType = document.getElementById('<%=ddlqoutatfileType.ClientID %>').value;
var elements = document.getElementById("form1").elements;
for (var i = 0, element; element = elements[i++];) {
if (deOrderDate.GetValue() == null) {
alert("Please Enter Order Date");
return false;
}
if (Region == "None Selected" || null) {
alert("Please Select Region");
return false;
}
if (Depot == "Select" || null) {
alert("Please Select Depot");
return false;
}
if (deInqDate.GetValue() == null) {
alert("Please Enter INQ Date");
return false;
}
if (QUOFileType == "Select") {
alert("Please Select File Type");
return false;
}
}
}
What i need to change in that to fix this issues

Call javascript from textbox clear 'x' event

I have two fields where the user can only write in one or the other, we validate the client side using the javascript below. The problem that I have is that the textboxes by default have a clear 'x' that when used doesn't trigger the javascript leaving one of the fields disabled.
How can I call the javascript function when the user clicks the clear 'x' of the textbox in order to get both fields enabled?
<asp:TextBox ID="txtFIELD1Val" runat="server" onKeyup="javascript:clearFields();" TabIndex="1" CssClass="cssTextbox"></asp:TextBox>
<asp:TextBox ID="txtFIELD2Val" runat="server" onKeyup="javascript:clearFields();" TabIndex="2" CssClass="cssTextbox"></asp:TextBox>
function clearFields() {
var txtFIELD1 = document.getElementById('<%= txtFIELD1Val.ClientID %>');
var txtFIELD2 = document.getElementById('<%= txtFIELD2Val.ClientID %>');
//Enable/Disable FIELD1 and FIELD2 fields based on text.
if (txtFIELD1.value == "" && txtFIELD2.value == "") {
txtFIELD1.disabled = false;
txtFIELD2.disabled = false;
}
else if (txtFIELD1.value == "" || txtFIELD2.value != "") {
txtFIELD1.disabled = true;
txtFIELD2.disabled = false;
}
else if (txtFIELD1.value != "" || txtFIELD2.value == "") {
txtFIELD1.disabled = false;
txtFIELD2.disabled = true;
}
}
Remove IE10's "clear field" X button on certain inputs?
See the second answer, seems to be the best approach to getting rid of the 'X' and the problems it's causing.

Return false if no value is selected (other than heading) from select box

I have a HTML form having select box. On selection of first drop down, next drop down should be auto filled using AJAX.
On Download Records (id="getCsv") button click event a CSV file is generated. Problem is, I want to make all the fields mandatory. Here is the jquery code
var teacher_name = $("#sel_teacher option:selected").text();
var unittest_name = $("#sel_test1 option:selected").text();
var class_name = $("#sel_class1 option:selected").text();
var class_id = $('#sel_class1').val();
var division_name = $("#sel_div1 option:selected").text();
var division_id = $('#sel_div1').val();
var subject_name = $("#sel_sub1 option:selected").text();
if (teacher_name == "") {
alert('Please Select Teacher Name.');
return false;
} else if(class_name == "") {
alert('Please Select Class Name.');
return false;
} else if(division_name == "") {
alert('Please Select Division Name.');
return false;
} else if(subject_name == "") {
alert('Please Select Subject Name.');
return false;
} else if(unittest_name == "") {
alert('Please Select Unit Test Name.');
return false;
} else {
var myObject = new Object();
myObject.class_name = class_name;
myObject.class_id = class_id;
myObject.division_name = division_name;
myObject.division_id = division_id;
myObject.subject_name = subject_name;
myObject.test_name = unittest_name;
var formData = JSON.stringify(myObject);
$('#getCsv').attr('href','csv_generator.php?data=' + formData);
}
The problem is that when I click Download Records, even though the first select box is empty directly alert box for second select box pops up. I tried to solve this problem using the below, but no luck.
if ($("#sel_teacher").attr("selectedIndex") == 0) {
alert("You haven't selected anything!");
return false;
}
Can anybody please help me with this? Any help is appreciated.
selectedIndex is a property, use prop:
$("#sel_teacher").prop("selectedIndex")
Also, you can simplify your code by retrieving the selected value using just $("#sel_teacher").val() and compare to empty string (assuming the value of that option is empty).
var teacher_name = $("#sel_teacher").val();
// get other <select /> values here...
if (teacher_name == '') {
alert("You haven't selected anything!");
return false;
}
// test other values here...
It might be because of the default value that you have given for the first text-box.Just change the value to "" onclick or on blur on that text-box.
Or you can simply handle this matter via HTML5 attribute required and adding onchange() Event Listener .
<select name="sel_teacher" onchange="get_value();" id="sel_teacher" required>
<option>--Select Teacher Name--</option>
</select>
<script>
function get_value() {
var teacher_name = $("#sel_teacher").val();
// get other <select /> values here...
if (teacher_name == '') {
alert("You haven't selected anything!");
return false;
} else {
// write code when teacher_name is selected
}
}
</script>

Error in setting alert in radiobuttonlist?

I have a two text box with radiobuttonlist.If the two test are blank it should alert "textbox are blank" and if its not blank it should alert "date is enabled".
This what i have tried with javascript
function checked() {
var radio = document.getElementById('<%=rbtn1.ClientId%>');
var cal1 = document.getElementById('<%=textstqo.ClientId%>').value;
var cal2 = document.getElementById('<%=textedqo.ClientId%>').value;
if (radio.checked = true) {
if(cal1 == '' && cal2 =='')
{
alert("dates cannot be blank");
return false
}else
{
alert("dates are enabled");
return true
}
}
}
Radio button list
<asp:RadioButtonList ID="rbtn1" runat="server" RepeatDirection="Vertical" RepeatLayout="Table" Height="300px" Width="101px" onClick="checked()" >
<asp:ListItem Text="one" Value="one" Enabled="true"></asp:ListItem>
<asp:ListItem Text="two" Value="two" Enabled="true" ></asp:ListItem>
<asp:ListItem Text="three" Value="three" Enabled="true"></asp:ListItem>
Edited
Error: Function expected
The first alert is working .when i tried to check the alert in else part it shows the above error
I have only shown you the first radio button that is "quaterone" and the javascript is also for quaterone
Can anyone tell me what i am doing wrongly.Thanks in advance
Problem is you are using wrong id for the radio button. '<%=rbtn1.ClientId%>_Quaterone'
Try instead: '<%=rbtn1.ClientId%>'
Edited:
var radioCont = document.getElementById('<%=rbtn1.ClientId%>');
var radio = radioCont.getElementsByTagName('input')[0];//first radio
Also you are trying to assign value instead of comparison:
if (radio.checked = true) { //assignment
Try this:
if (radio.checked == true) { // though `===` is recommended over `==`
You may also try:
if(radio.checked) {
// to do here
}
Change the attribute to onchange instead of onclick, here:
onClick="checked()" >
In order to uncheck the radio assign false to its state:
alert("dates cannot be blank");
radio.checked = false; //un-check the radio
return false;
To validate only when the first radio button is checked, you can check it like
if($('#rbtn1 input:radio:checked').val() == 'quaterone'){
// your condition here...
}

Why isn't this simple javascript working?

This javascript all but works with exception of radiobuttonlist.
<script language="javascript" type="text/javascript">
function validate() {
if (document.getElementById("<%=txtballotName.ClientID%>").value == "") {
alert("Ballot Name can not be blank");
document.getElementById("<%=txtballotName.ClientID%>").focus();
return false;
}
if (document.getElementById("<%=txtballotCity.ClientID %>").value == "") {
alert("Ballot City can not be blank");
document.getElementById("<%=txtballotCity.ClientID %>").focus();
return false;
}
if (document.getElementById("<%=txtballotState.ClientID%>").value == "") {
alert("Ballot State cannot be blank");
document.getElementById("<%=txtballotState.ClientID%>").focus();
return false;
}
if (document.getElementById("<%=txtballotZip.ClientID%>").value == "") {
alert("Zip Code cannot be blank");
document.getElementById("<%=txtballotZip.ClientID%>").focus();
return false;
}
if (document.getElementById("<%= txtreceivedby.ClientID %>").checked == false) {
alert("Request Received By can not be blank");
document.getElementById("<%=txtreceivedby.ClientID%>").focus();
return false;
}
return true;
}
The radiobuttonList looks like this:
<tr>
<td>
<label for="txtreceivedby_0">FAX</label>
<input id="txtreceivedby_0" type="radio" name="txtreceivedby" value="Fax" />
</td>
<td>
<label for="txtreceivedby_1">EMAIL</label>
<input id="txtreceivedby_1" type="radio" name="txtreceivedby" value="Mail" />
</td>
<td>
<label for="txtreceivedby_2">PHONE</label>
<input id="txtreceivedby_2" type="radio" name="txtreceivedby" value="Phone" />
</td>
</tr>
So far, the other form field are validating except the txtreceivedby radio button. I am not getting any errors but it isn't validating either.
Thanks in advance
You can create a short little utility function that will get you the value of any radio group:
function getRadioValue(name) {
var items = document.getElementsByName(name);
for (var i = 0; i < items.length; i++) {
if (items[i].checked) {
return(items[i].value);
}
}
}
You can then get the checked item in your radio group like this:
var val = getRadioValue("txtreceivedby");
Working Demo: http://jsfiddle.net/jfriend00/PHXaC/
ASP's radiobuttonlist render as a table containing radio button items. Therefore, it is a bit complicated to get the checked status of radio button.
You might find various sources if you google for "ASP radiobuttonlist and javascript". I have tested some of them and not every of them worked well specially if your page created from Master page.
However, I have tried in my own way and here it is:
<asp:RadioButtonList ID="txtReceivedBy" runat="server">
<asp:ListItem Text="Fax" Value="0"></asp:ListItem>
<asp:ListItem Text="Email" Value="1"></asp:ListItem>
<asp:ListItem Text="Phon" Value="2"></asp:ListItem>
</asp:RadioButtonList>
<input type="button" onclick="alert(checkedRadio());" value="Test RadioButtonChecked Status" />
and the javascript I have used to get the cehcked status is here
function checkedRadio() {
var rtn = false;
var i = 0;
var radioBoxesContainer = document.getElementById("<%=txtReceivedBy.ClientID%>");
if (radioBoxesContainer) {
var radioBoxes = radioBoxesContainer.getElementsByTagName("input");
if (radioBoxes && radioBoxes.length > 0) {
for (i - 0; i < radioBoxes.length; i++) {
if (radioBoxes[i].checked) {
rtn = true;
break;
}
}
}
}
return rtn;
}
if you are interested to get a live demo,
you can find it here http://plugins.amiwithyou.com/sof/
In a nutshell major headache; if you'd page me, I'd go with a nice good ol' fashion <select> box.
But to be useful, you need to have a look with view source at exactly what the ASP code plasts out to the browser. I don't know ASP but I bet it's either outputting 3 different ids on each radio, or the same id (#txtreceivedby) on all three of them.
Whatever it gives out, the validation code if(bla_bla_blah.checked===false) is wrong because it only targets just one in the set of radios and even with that fixed, that radio might not return .checked===false cross-browser.

Categories

Resources