Tips on obtaining checkbox values other than "true"

Having trouble retrieving the values of selected checkboxes instead of displaying "Custom Category"? I've attempted to access the values and attributes with no success.

I'm aiming to display the values of the selected checkbox.

app.component.html

<form #myForm="ngForm">
<div class="form-group">
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="dl1" required #dl="ngModel" value="DL1" ngModel name="dl">
<label class="form-check-label" for="">DL 1</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="dl2" required #dl="ngModel" value="DL2" ngModel name="dl">
<label class="form-check-label" for="">DL 2</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="dl3" required #dl="ngModel" value="DL3" ngModel name="dl">
<label class="form-check-label" for="">DL 3</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="dl4" required #dl="ngModel" value="DL4" ngModel name="dl">
<label class="form-check-label" for="">DL 4</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="dl5" required #dl="ngModel" value="DL5" ngModel name="dl">
<label class="form-check-label" for="">DL 5</label>
</div>
<div *ngIf="dl.invalid" class="error">Please select at least one DL.</div>
</div>
<div class="form-group">
<label>Comments</label>
<textarea name="comments" #comments="ngModel" required class="form-control" ngModel id="" cols="5" rows="5"></textarea>
<span *ngIf="comments.invalid && comments.touched" class="error"& Return gt;Please provide your comments.</span>
</div>
<div class="form-group">
<button type="submit" [disabled]="myForm.invalid" class="btn btn-primary btn-sm" (click)="addSubData(myForm.value)">Submit</button>
<button type="button" class="btn btn-secondary btn-sm ml-2" (click)="cancelAddUser()">Cancel</button>
</div>
</form>

app.component.ts

addSubData(user: any) {
let newData = this.userObj.assigned_to;
let i: any;
i = document.querySelectorAll('input[type="checkbox"]:checked').length;
for (let j=1; j<=i; ++j) {
newData.push(user);
user.dl = "Custom Category";
console.log(user.dl); 
}
user.sub_impact = "Applicable";
user.co_score = "Added";
this.commonService.updateUser(this.userObj).subscribe(()=> {
this.getLatestUser();
});
}

Output https://i.stack.imgur.com/NY1DG.png

Live:

Answer №1

As per the guidelines, an input of type="checkbox" only has two possible values, true or false. It also mentions the importance of using preset "values." There are two approaches to achieve your desired outcome:

  1. Utilize element.id.toUpperCase()
  2. Implement Data attributes

Answer №2

Does this brief example offer any assistance?

const test = () => {
    const selected = [...document.querySelectorAll('input[type="checkbox"]:checked')].map(cb => {
    return cb.value;
    });
  console.log(selected);
}
<input class="form-check-input" type="checkbox" id="dl1" required #dl="ngModel" value="DL1" ngModel name="dl">
<label class="form-check-label" for="">DL 1</label>
<input class="form-check-input" type="checkbox" id="dl2" required #dl="ngModel" value="DL2" ngModel name="dl">
<label class="form-check-label" for="">DL 2</label>
<button onclick="test()">Test</button>

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

Django fetches and returns a solitary record in JSON format

In our web admin, I have implemented a form using jQuery and Ajax to add notes about a customer. The goal is for the Django view to return the newly added note after submission so that it can be displayed in the customer notes table. While the Ajax send fu ...

I'm puzzled as to why this code snippet consistently produces a range of 50 to 100 repeated values. This piece of code is crucial for altering the behavior of a function based on a specific

Below is a snippet of my React code aiming to alter the functionality of a function based on a specific window width: const [windowWidth, setWindowWidth] = useState({ winWidth: 0 }); useEffect(() => { window.addEventListener('resize', ( ...

What is the process for setting up Vue.js and using it in conjunction with Sails JS?

After successfully setting up the backend of my website using Sails JS, I decided to integrate Vue.js into my project. Following the installation of Vue and VueResource through npm install --save, I created an app.js file in my assets/js folder. However, ...

update the markers on a leafletjs map

I am aiming to create a dynamic map with markers that update every 10 minutes. The marker positions are stored in a spreadsheet document that is regularly updated. After successfully retrieving the data from the spreadsheet and positioning the markers in ...

Angular Universal in Angular 6 - No need to wait for content API request

Struggling to enable SSR with Angular Universal for pages containing dynamic content. All static pages work fine, but the dynamic pages are rendered without the dynamic data. Method Executed: ngOnInit() { const div = this.renderer.createElement('d ...

"Combine data streams efficiently with RxJS using #groupBy to create groups of observable

I am trying to zip grouped observables in order to form the cartesian product of related groups. However, when I run the code below, only the child observable groups emit values inside the #zip function - why is that? Link to code snippet var parent = Rx ...

Tips for customizing the WooCommerce product page

If you want to customize the layout of a WooCommerce product page, you can override the template by copying the WooCommerce template folder into your theme. You can find step-by-step instructions here. I am looking to change the layout of a WooCommerce pr ...

Using Jquery to dynamically adjust the size of a div based on the width and height of the browser window

How can I dynamically change the height of a .test div based on the browser width and height? I want the value to update whenever the browser is resized. $(document).ready( function() { window.onresize = function(event) { resizeDiv(); ...

Ensure that you include validation in the ajax request when loading the message content from a separate file

ajax code for adding data to the database <script type="text/javascript"> $(function() { $(".submit_button").click(function() { var textcontent = $("#content").val(); var dataString = 'content='+ textcontent; if(textcontent=='') ...

Should we consider the implementation of private methods in Javascript to be beneficial?

During a conversation with another developer, the topic of hacking into JavaScript private functions arose and whether it is a viable option. Two alternatives were discussed: Using a constructor and prototype containing all functions, where non-API meth ...

As you scroll, a box blocks off half of the screen

Hey everyone, I could really use your assistance! I'm working on developing a javascript code and here is the idea - if anyone can contribute to it. It's like a social media platform where users enter the site and the is_user_logged_in parameter ...

Expand the scope of the javascript in your web application to cater

I am in the process of creating a web application that utilizes its own API to display content, and it is done through JavaScript using AJAX. In the past, when working with server-side processing (PHP), I used gettext for translation. However, I am now ...

Issues with the plugin for resizing text to fit the parent div's scale

I've spent the last hour attempting to get this script to function properly, but no luck yet. Check out the correct jsfiddle example here: http://jsfiddle.net/zachleat/WzN6d/ My website where the malfunctioning code resides can be found here: I&apo ...

I have created a textbox with a button, but I am unsure of how to delete it

var emailFields = document.getElementById('emails'), addLinkButton = document.createElement('a'), fieldTemplate = emailFields.getElementsByTagName('div'), currentFieldCount = fieldTemplate.length, maxFields ...

Invoke a method within a function triggered by the .call() method

Currently, I am developing an n8n node that essentially functions every time a specific event occurs. To facilitate this process, I have created an abstract class which is invoked by the n8n environment. However, there seems to be a limitation in calling ...

When a change occurs in the <input/> element within a <div>, the onChange event in React will be triggered

Upon entering text into the input, the onChange function is triggered on this code snippet. How is it possible for the onChange event to occur on a div element? Is there documentation available that explains this behavior? class App extends Component { ...

How can I retrieve the express Application within a REST API?

After reviewing Massive's documentation and learning that saving the connection object to Express's application settings can help reduce database connection execution time, I encountered a problem. How can one access the Express app variable when ...

What is the best way to implement a scroll event in a React application?

Can someone provide guidance on how to properly write the scrollHandler function for this scenario? ` useEffect(() => { document.addEventListener('submit', scrollHandler); return () => document.removeEventListener('scroll', ...

Encountering a JSONDecodeError with the message "Expecting value: line 1 column 1 (char 0), I have come across this

Looking for a solution to the JSONDecodeError: Expecting value: line 1 column 1 (char 0) error? Check out the code snippet provided below: from urllib.request import urlopen api_url = "https://samples.openweathermap.org/data/2.5/weatherq=Lon ...

Cease the animated loading icon once the template has finished loading in sync with the async pipe

.ts initialize() { const loadingScreen = await this.loadingService.displayLoader();//loading screen this.products$ = this.bikeShopService.retrieveData();//Observable operation } .html <ion-col size="6" *ngFor="let product of (products$ ...