Integrating Javascript with ASP.NET using RadioButtonList

Welcome to my Default.aspx page

                <td>Radio Control</td>
                <td>
                 <asp:RadioButtonList ID="RadioButtonList1" runat="server" >
                    <asp:ListItem Text = "One" Value = "1"></asp:ListItem>
                    <asp:ListItem Text = "Two" Value = "2"></asp:ListItem>
                    <asp:ListItem Text = "Three" Value = "3"></asp:ListItem>
                </asp:RadioButtonList>
                </td>
                <td><div id="Div1" style="color:Red;display:none"></div></td>
            </tr>

            <tr>
                <td>Dropdown Menu </td>
                <td>
                    <asp:DropDownList ID="DropDownList1" runat="server" >
                         <asp:ListItem>Select</asp:ListItem>
                         <asp:ListItem>Male</asp:ListItem>
                         <asp:ListItem>Female</asp:ListItem>
                    </asp:DropDownList>
                </td>                   
            </tr>
        </table>    
<br />
<center> 
        <asp:Button ID="Button1" runat="server" Text="Edit"/>
        <asp:Button ID="Button2" runat="server" Text="Choose from Dropdown" OnClientClick="return ValidateDropDown('DropDownList1');" />
        <asp:Button ID="Button3" runat="server" Text="Validate Radio" OnClientClick = "return ValRad(document.getElementById('RadioButtonList1'));" />
</center>

This is a script from my separate JavaScript file:

function ValRad(CntrlID) {
          alert("Checking Radio Buttons");
          var RB1 = CntrlID;
          alert("Processing..");
          var radio = RB1.getElementsByTagName("input");
          alert("Verifying..");
          var isChecked = false;
          alert("Proceeding..");
              for (var i = 0; i < radio.length; i++) {
              if (radio[i].checked) {
              isChecked = true;
              break;
              }
         }
         if (!isChecked) {
         alert("Please select an item");
       }
     return isChecked;    
   }

I am facing issues validating both the radiobuttonlist and dropdownlist, any help would be greatly appreciated. Apologies for any formatting errors as I am new here.

Answer №1

When using a Radio Button List, you can implement the RequiredFieldValidator for validation.

  <asp:RadioButtonList ID="rblChoose" runat="server" RepeatDirection="Horizontal" 
 RepeatLayout="Flow">
   <asp:ListItem Text="a" Value="a" />
   <asp:ListItem Text="b" Value="b" />
</asp:RadioButtonList>
<asp:RequiredFieldValidator ID="rfvChoose" runat="server" 
ControlToValidate="rblChoose" ErrorMessage="Choose option." 
ForeColor="red" SetFocusOnError="true"></asp:RequiredFieldValidator>

For validating a DropDown

<asp:DropDownList runat="server" id="ddl">
<asp:ListItem Value="0" text="Select a Value">
....
</asp:DropDownList>

<asp:RequiredFieldValidator ID="rfv1" runat="server" ControlToValidate="ddl" InitialValue="Please select" ErrorMessage="Please select something" />

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Looking to retrieve the dynamic "Publish Date" value from a webpage using HtmlUnit in Java?

As part of a coding exercise, I am currently working on a project that involves comparing the current system date with dates on various web pages to determine if there are any new updates. While most of the pages work as expected, there is one particular p ...

Utilize Devextreme's dxDataGrid component to transmit the selected RowData to a function upon clicking a button within that particular row

I am utilizing the dxDataGrid user interface widget from the Devextreme product. My goal is to transform one of its columns into a clickable button. Here is my progress so far: Field Configuration { dataField: 'LetterNumber', caption: ' ...

Serializing ASP.NET WebApi's DateTimeOffset to Json/JavaScript in Angular2

Struggling to properly handle a DateTimeOffset value for JavaScript (specifically angular2). RecordModifiedAt : "2016-03-08T17:27:11.9975483+01:00" Unfortunately, JavaScript/angular2 doesn't seem to recognize this as a valid datetime value. I have ...

Manipulating vertices in Three.js

I am fairly new to Three.js and I am attempting to create a basic PlaneGeometry. The process would involve: The user will specify their preferred height and width for the PlaneGeometry The browser will then render the plane with the height and width ...

Unable to locate registration for type 'Microsoft.Framework.Runtime.ILibraryManager' service

Currently, I am working on a project involving the new version of ASP.NET. Every time I try to run an empty ASP.NET project, I encounter a frustrating error. The project only consists of generated code, and despite my attempts to change the CLR's sett ...

(Node.js Fundamentals) Is there a specific reason for placing a period in front of the pathname following the parsing of a

As a beginner in Node.js, I decided to follow a tutorial on w3school to deepen my understanding of this platform. var http = require('http'); var url = require('url'); var fs = require('fs'); http.createServer(function (req ...

Redefining a path in JavaScript after the page has already loaded

I am currently facing an issue with my website, which is built in HTML. In the head tag, I have included a JavaScript file. The website consists of two pages, and the problem arises when the path defined in the JavaScript file works correctly on the first ...

Incorporating external CSS links in the metadata of Next.js 13

A recent update in Nextjs 13 introduced a new feature known as Metadata (https://nextjs.org/docs/app/api-reference/functions/generate-metadata), causing the removal of Head.js. Previously, I would import a CSS file using the <Head> tag as shown below ...

When trying to render a list of items, an error occurs stating that the type void cannot be assigned to type React

Recently, I came across a coding snippet that aims to loop through an object's key-value pairs and display them in a list. import { PersoanaType } from "./PersoanaType"; type Props = { persoana: PersoanaType } export default function P ...

What is the best method for designing a slideshow with a background image on the body

I have been on a quest to find a simple background slideshow that fades images for the body of my website. Despite trying multiple Javascript options and CSS solutions, I have had no success. Someone suggested creating a DIV for the background, but I am ...

How can I trigger a page postback in ASP.NET after downloading a file?

Here is my current scenario: The user clicks on a LinkButton, triggering a PostBack on the page. However, I also need to initiate a file download for the user simultaneously. To achieve this, I added the following code to the LinkButton: lnkPrint.Attri ...

Error: Discord bot encountered a TypeError while attempting to access the property 'id' of an undefined value

After revisiting a previous Discord bot package designed to track website updates, I encountered an issue. The code was originally scraped and last edited about 8 months ago with success. However, upon running node index.js, the following error occurred. ...

Accessing the jQuery Ajax success variable

I have a PHP function that returns an array with an element error containing the value 'ERR': var updatePaymentType = function(plan_pt_id, pt_id){ var error = null; var data = new Object() data["function"] = "update"; ...

Finding unique data stored in separate JSON files and loading them individually may require using different methods for

I have two JSON files named marker.json and marker.json0 that contain different latitude and longitude coordinates. To load them, I need to rename .json0 to .json (and vice versa), so that the new data from marker.json0 now resides in marker.json. This way ...

Invoking an Angular function with jQuery when a button is clicked

I am trying to trigger a method in an Angular controller using a jQuery button click event. Here is the HTML code snippet: <div class="actionBar"> <select class="select select-primary form-control" id="ClassificationS ...

Discovering and swapping values within nested objects

I've encountered a challenge that I need help with: In my nested object, I receive a response from the server containing an object with updated values. My goal is to locate this object within my nested structure and replace it. The structure of my o ...

Tips for implementing multiple nested routes using Vue.js?

Can Nested Routes be created with more than 2 levels? I am looking to implement a structure like this: +--------------------+ | User | | +----------------+ | | | Profile | | | | +------------+ | | | | | About | | | | | | +------ ...

Configuring v-model with dynamic attribute in Vue.js

Is it possible to dynamically set up v-model using v-for with dynamic keys? The current code does not seem to update the model as expected. I am working within the Vuetify framework. Here is my code snippet: Template <v-card v-for="(value, key) in ...

Encountering an Unexpected Token error while using the getjson function

I need help parsing JSON data from an API feed, but I'm having trouble getting the JSON to parse correctly into an array. Here's a snippet of my JSON file. You can find the full file at the following location: JSON location: { "odata.metadata ...

Accessing and sending only the body part of an HTTP response in Angular 7 test cases: A comprehensive guide

Currently, I am working on creating unit test cases in Angular 7 for a Component that utilizes an asynchronous service. This is the content of my component file: submitLoginForm() { if (this.loginForm.valid) { // send a http request to save t ...