Setting a radio button to be checked in AngularJS using stored data

I am facing an issue with the radio button for the account type. Even though it is correctly stored in the database, it does not display when I first load the page. However, upon clicking any of the radio buttons, it updates the value and shows as checked.

The account.accountType is defined as an enum with three options: internal = 0, customer = 1, or proposal = 2. It can also be null initially until a selection is made, in which case nothing will be checked. How can I resolve this issue?

My setup involves Angular version 1.4.9 and I am using TypeScript for the controller.

<div class="form-group" 
ng-class="{ 'has-error': accountForm.$submitted && accountForm.accountType.$invalid }">
          <label for="customerName">Account Type:</label>
             <div>
                <label class="radio-inline">
                   <input type="radio" name="accountType" 
                   id="internal" value="0" ng-model="account.accountType" 
                   ng-required="true" ng-checked="account.accountType == 0"> Internal
                </label>
                <label class="radio-inline">
                   <input type="radio" name="accountType" 
                   id="customer" value="1" ng-model="account.accountType" 
                   ng-required="true" ng-checked="account.accountType == 1"> Customer
                </label>
                <label class="radio-inline">
                   <input type="radio" name="accountType" id="proposal" 
                   value="2" ng-model="account.accountType" ng-required="true" 
                   ng-checked="account.accountType == 2"> Proposal
                </label>
             </div>
<p class="text-danger" ng-if="accountForm.$submitted && accountForm.accountType.$invalid">Please select an account type.</p>
</div>

Answer №1

//

update the account.accountType value in your controller to automatically check the corresponding //checkBox.
//for instance, setting account.accountType to 2 with ng-init will result in the second checkbox being checked upon loading

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="" ng-init="account.accountType = 2" class="form-group" ng-class="{ 'has-error': accountForm.$submitted && accountForm.accountType.$invalid }">
  <label for="customerName">Account type:</label>{{account.accountType}}
  <div>
    <label class="radio-inline">
                   <input type="radio" name="accountType" 
                   id="internal" value="1" ng-model="account.accountType" 
                   ng-required="true" ng-checked="account.accountType == 1"> Internal
                </label>
    <label class="radio-inline">
                   <input type="radio" name="accountType" 
                   id="customer" value="2" ng-model="account.accountType" 
                   ng-required="true" ng-checked="account.accountType == 2"> Customer
                </label>
    <label class="radio-inline">
                   <input type="radio" name="accountType" id="proposal" 
                   value="3" ng-model="account.accountType" ng-required="true" 
                   ng-checked="account.accountType == 3"> Proposal
                </label>
  </div>
  <p class="text-danger" ng-if="accountForm.$submitted && accountForm.accountType.$invalid">Please choose an account type</p>
</div>

Answer №2

It is important to avoid combining the ng-checked directive with ngModel due to the potential for unpredictable outcomes. Consider using the following approach for each radio button:

<input type="radio" name="accountType"
                   id="internal" value="0"
                   ng-required="true" ng-checked="account.accountType == 0">

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

What is the solution for fixing an error that says "There is no 'style' property on the 'Element' type"?

I'm struggling to fix an error in my JavaScript code. I created a script to display a tab indicator when a tab is clicked, but I keep getting the error message: "Property 'style' doesn't exist on type 'Element'". The tabs them ...

Issue with TypeORM Many-to-Many relation returning incorrect data when using the "where" clause

I'm facing an issue with my database tables - User and Race. The relationship between them is set as Many to Many , where a Race can have multiple Users associated with it. My goal is to retrieve all the Races that a particular user is a member of. Ho ...

Combine two or more Firebase Observables

Currently, I am working on creating an Observable using FirebaseObjectObservable. However, before I can accomplish this, I need to query a Firebase list to obtain the key IDs required for the FirebaseObjectObservable. The structure of my data is as follow ...

Pass information from an array of objects to a visual component

My objective is to display 3 instances of the SearchItem component from locations[0].results[0] and 3 instances from locations[0].results[1] I have an array containing objects with data that I want to display in my SearchItem component: const locations = ...

I'm interested in learning more about how to select or deselect all checkboxes

How can I uncheck the "all" checkbox when I uncheck another checkbox? $('#All').click(function () { var status = $(this).is(":checked"); if (status) { $.each($('input[name="checkbox"]'), function () { this. ...

Implementing JavaScript to Retrieve and Insert Full HTML Tags into a Textarea

I am currently trying to extract an HTML source code value and insert it into a specific textarea or div upon clicking a button. However, I am encountering issues where I am not receiving the entire HTML tags - it seems to begin with a Meta tag and is remo ...

Substitute all instances of <table> with <div> tags, making sure to include specifications for

Currently, I find myself immersed in a project that relies heavily on tables, which isn't exactly ideal but is what the marketing department insists upon... To tackle this issue, I have implemented jQuery to convert all tables into DIVs, and so far, ...

Using destructuring repeatedly for a single object property

At times, I engage in nested destructuring, where I go more than one level deep. It can be risky, but I always make sure the property exists to avoid encountering an error of undefined. Recently, I came across this scenario: const { match: { ...

Develop a novel function

I am working on a new Order page where users can select a category, then a service, and fill out the quantity field for their order. I have an idea to create a function using @if and @else statements. In this function, I want to display the quantity fiel ...

Mapping over an array and ignoring any undefined properties in a dynamic object

Looking for a way to dynamically create objects in the 'map' function to reduce the final array size. The goal is to avoid adding properties with undefined values. For example, if 'offst: undefined', skip this property but add others wi ...

Tips for restricting users from inputting spaces into a form field using ReactJS

Within my application, I have developed a specialized component named QueryForm that serves the purpose of enabling search capabilities. The code snippet being outputted by this component is as follows: ...

Long X-axis labels on D3 chart causing overlap issue

I am facing an issue with my D3 Bar chart where the X-Axis labels are overlapping. Here is the code snippet that I have: // implementing word wrapping for x axis svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height ...

When trying to update a Mobx store observable from within itself, you may encounter an error message stating "Unable to access property of <observable> as it is undefined."

Although I am aware of similar issues that have been discussed before, I couldn't find a solution to my specific problem after reviewing many of them. Let me explain the situation: In my scenario, I need my ReportStore to retrieve data from the serve ...

The radio button update functionality in codeigniter is not reflecting changes in the database via ajax

There seems to be an issue with the radio button functionality. When selecting the second option, it remains stuck on the first option. AJAX Code: $(document).ready(function(){ $('#btn_update').on('click',function(){ var id = ...

Implementing dynamic rotation of a cube in A-Frame using Javascript

I have been experimenting with A-Frame and Socket.io recently. I have successfully managed to rotate a cube/box statically using the following HTML code: <a-box position="-1 0.5 -3" rotation="0 0 0" color="#4CC3D9"> <a-animation id="cube ...

JavaScript versus Non-JavaScript Links and Forms: A Comparison

The other day, I posted a query that got me thinking: Comparing AJAX link with normal link It revolved around the idea of creating links that function for JavaScript-enabled browsers using AJAX, while also providing a normal link for non-JavaScript brows ...

Guide to implementing a Bootstrap dropdown in an Angular application

I am implementing a bootstrap dropdown with checkboxes and looking to integrate it into Angular. http://codepen.io/bseth99/pen/fboKH (I have made modifications like wrapping the dropdown in a form) <form> <div class="container" ng-controller ...

Guide on displaying a JSON file from a separate port in Symfony2

Just diving into symfony2 and encountering a little challenge here. I've got my localhost all set up using wamp server with some port assignments: Port 80 (default) for symfony: mylocal/app_dev.php/test Port 8080 for the public folder: mylocal:8080/cs ...

The dynamic duo of AngularJS and Kendo UI

Hey there! I'm currently working with Angular JS and Kendo UI in my application, but I've run into a peculiar error that's got me stumped. The error reads: TypeError: object is not a function TypeError: Function expected at Anonymous functi ...

Encountering an error stating "Argument of type 'X' is not assignable to parameter of type 'X' in the NextApiResponse within NextJS."

Here is the code snippet I am working with: type Data = { id: string; name: string; description: string; price: number; }; const FetchMeals = async (req: NextApiRequest, res: NextApiResponse<Data>) => { const response = await fetch( ...