Capture the checked checkbox value and store it as a string

Is there a way to save the value from a checkbox into a string?

 <label style="color:black; text-decoration:none; font-size:15px" href="#">
                  <input type="checkbox" ng-model="diet.v1" ng-true-value="'&diet=high-fiber'" ng-false-value="''" />High-Fiber</label> 

I am trying to figure out how to extract the value from ng-true-value when the checkbox is checked, and store it in a string for later use. However, using console.log(diet.v1); in JavaScript does not seem to work. Any suggestions on how to achieve this?

Answer №1

Take a look at this demonstration code featuring the ng-true-value and ng-false-value directives.

 <!doctype html>
        <html lang="en">
        <head>
          <meta charset="UTF-8>
          <title>Sample - example-checkbox-input-directive-production</title>
          
        
          <script src="//code.angularjs.org/snapshot/angular.min.js"></script>
          
        
          
        </head>
        <body ng-app="checkboxExample">>
          <script>
          angular.module('checkboxExample', [])
            .controller('ExampleController', ['$scope', function($scope) {
              $scope.diet = {
               v1 : ''
             };
            }]);
        </script>
        <form name="myForm" ng-controller="ExampleController">
          <label>Value:
            <input type="checkbox" ng-model="diet.v1"
                   ng-true-value="'&diet=high-fiber'" ng-false-value="''">
           </label><br/>
          <tt>value = {{diet.v1}}</tt><br/>
         </form>
        </body>
        </html>

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 best way to monitor a variable using the controllerAs syntax in Angular?

When utilizing the standard controller syntax in AngularJS, you have the ability to watch a variable with code like this: $scope.$watch(somethingToWatch, function() { alert('It changed!'); }); However, with the controllerAs syntax, how can I ea ...

Is it possible for elasticsearch to calculate a cumulative total for a numerical field as it runs?

When utilizing a facet such as "histogram": { "key_field": "timestamp", "value_field": "amount", "time_interval": "1d" } The resulting set includes the following: { key: 1222732800000 count: 642 min: -985 max: 483.25 total: 154 ...

Integration issue: React.js is failing to render within a Django project

I have been working on a project where React is not rendering anything on Django localhost. index.html <!DOCTYPE html> <html lang="en"> <head></head> <body> <div id="App"> <!---all will b ...

Error: Failed to cast value "{ email: 'example@email.com' }" to ObjectId (type Object) for the "_id" path in the "User" model

How can I use the Mongoose ID to fetch data and send it to the client's browser? My Mongoose Database Data: {"_id":{"$oid":"6404fc0b9e6a0640b0deb716"},"username":"dddd","email":"[email&# ...

When Vue.js Vuex state changes, the template with v-if does not automatically refresh

I have tried setting the v-if value in computed, data, passing it as props, and directly referencing state, but it never seems to re-render despite the fact that the state I am checking for is changed to true. Currently, I am directly referencing the stor ...

The type 'Dispatch<SetStateAction<boolean>>' cannot be assigned to type 'boolean'

Currently, I am attempting to transfer a boolean value received from an onChange function to a state variable. let [toggleCheck, setToggleCheck] =useState(false);` <input type="checkbox" id={"layout_toggle"} defaultChecked={toggleCh ...

Utilizing socket.io and NodeJS to manage turns in a turn-based gaming scenario

My game development project involves using Nodejs in combination with Socket.io to create a turn-based game. In this game, each player's turn must come to an end when either the "Pass" button is pressed or if 5 seconds have passed since the turn star ...

Small collapse Bootstrap navbar on col-sm width

I recently started experimenting with Bootstrap and implemented a collapsable navbar on my website. However, I noticed that on my Galaxy S6 phone, the navbar does not collapse into the button as expected when the screen size is reduced. Is there a way to ...

Retrieve request body/header variables in JWT strategy using Nest JS

Is there a way to retrieve the header variables or request body in a strategy? The JWT structure within the JwtStrategy currently appears as follows: @Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { constructor( private re ...

Express.js Issue: Error in JSON Object Returned When Date Parameter is Empty

Currently tackling the challenges of the FreeCodeCamp Timestamp Microservice project and facing a roadblock in the implementation. While most requirements are met successfully, there's an issue with handling an empty date parameter test case. Let me b ...

The initial output of the object yields an undefined value

Issue Description (View Code on Fiddle): The issue with this code is that the first printed result returns 'undefined'. Why does this happen and how can it be fixed? Code Snippet: var animals = { dogs: 0, cats: 0, birds: 0, fis ...

Tips on personalizing chosen date formats within the Mantine DatePicker?

I've integrated the Mantine DatePicker into my web application and now I want to customize the default style for when a user selects a date. Here's the current style: https://i.sstatic.net/hjQOi.png This is what I'm aiming for: https://i ...

- "Is it possible to extract values from an optional variable?"

Is there a method to access individual variables from the data returned by the reload method? let reloadProps: ReloadProps | undefined; if (useClientSide() === true) { reloadProps = reload(props.eventId); } const { isTiketAdmin, jwt, user ...

What is the meaning of this CSS acronym?

div[id^=picture]:target{ /*applying various styles here*/ } I stumbled upon the snippet of code shown above on a website discussing CSS image galleries. Can anyone clarify what this code accomplishes? Appreciate it. ...

What is the proper way to provide parameters in a GET request using Axios?

Recently, I have been attempting to include the api_key in the get request parameter using axios Below is the snippet of my code: const instance = axios.create({ baseURL: "https://api.themoviedb.org/3" }); export function crudify(path) { function get ...

AngularJS is throwing a RangeError, indicating that the time value is invalid when calling Date.toISOString

For my project, I need to display the date picker in jQuery (angular-jquery-datepicker) with the date formatted correctly for the user's timezone. I can successfully show dates in both USA and EU formats. When the user sets these dates, I have to save ...

updating react state based on filtered redux properties

Just starting out with react & redux and running into some issues with filtering insights (articles, case studies, reports). My goal is to filter by industry, but I'm struggling to update the state with the filtered insights. InsightsPage.js con ...

Validation does not occur when the submit button has an ng-click event attached to it

This is the form I created: <form action="" ng-controller="forgotCtrl as forgot" name="forgotForm"> <div class="form-group row"> <label for="email" class="col-sm-2 form-control-label">Email address</label> ...

Is there a way to incorporate tailwind classes into each react component when utilizing the map() function?

While working on a React Movie app, I encountered an issue with the tailwind class mx-auto. It was not applying properly to all items in the array; only the first element was affected. const MoviesList = () => { return( <div className=&a ...

What is the best approach to managing undefined properties retrieved from the html in my Angular application prior to obtaining data from my controller?

Every time my Angular component HTML renders, I encounter numerous errors that all look similar to this ERROR TypeError: Cannot read properties of undefined (reading 'someProperty') Throughout my HTML page, there are many bindings that follow ...