Implementing a functionality in Angular.js to automatically populate an input field when a checkbox is checked

My goal is to set the respective input field to a specific value when a checkbox is checked. Below is an example of what I am trying to achieve.

<label class="checkbox-inline">
    <input type="checkbox" name="favoriteColors"> Five
</label>
<label class="checkbox-inline">
    <input type="checkbox" name="favoriteColors"> Ten
</label>
<input type="text" name="color" id="clr" ng-model="color" readonly />

When the user checks the "Five" checkbox, I want the input field to display the number 5. Similarly, if the user checks the "Ten" checkbox, the input field should show the number 10.

Answer №1

utilize ng-true-value="" in a checkbox element

Follow this example

<label class="checkbox-inline">
    <input type="checkbox" ng-model="color" ng-true-value="5" ng-false-value="0" name="favoriteColors"> Five
</label>
<label class="checkbox-inline">
    <input type="checkbox" ng-model="color" ng-true-value="10" ng-false-value="0" ng-model="color" name="favoriteColors"> Ten
</label>
<input type="text" name="color" id="clr" ng-model="color" readonly />

JSFIDDLE

Answer №2

It seems like using radio buttons instead of checkboxes would be more appropriate in this scenario (since the color can only be either 5 OR 10). Here's a functional plnkr.

Here is the code snippet:

<label class="checkbox-inline">
    <input type="radio" name="favoriteColors" ng-model="data.color" value="5"> Five
</label>
<label class="checkbox-inline">
    <input type="radio" name="favoriteColors" ng-model="data.color" value="10"> Ten
</label>
<input type="text" name="color" id="clr" ng-model="data.color" readonly />

Javascript:

app.controller('MainCtrl', function($scope) {
  $scope.data = { color: '' };
});

Answer №3

<label class="checkbox-inline">
    <input type="checkbox" ng-click="chosenColor=5" name="preferredColors"> Five
</label>
<label class="checkbox-inline">
    <input type="checkbox" ng-click="chosenColor=10" name="preferredColors"> Ten
</label>
<input type="text" name="colorChoice" id="clrSelected" ng-model="chosenColor" readonly />

https://jsfiddle.net/9v7g3yho/4/

Answer №4

Connect your checkbox selections with the ng-model attribute and then assign values accordingly. Here is an example:

<input type="checkbox" name="favLetters" ng-model="isSelected.A"> A
<input type="checkbox" name="favLetters" ng-model="isSelected.B"> B

In your script:

$scope.isSelected = {};
if ($scope.isSelected.A) {
  $scope.letter = 'A';
}
if ($scope.isSelected.B) {
  $scope.letter = 'B';
}

By using two-way binding, the input value will automatically update as you toggle the checkboxes.

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

"React - encountering issues with state being undefined when passing child state up through parent components

I am currently navigating the world of react and have encountered a hurdle. I find myself facing difficulties in updating the parent component based on changes in the child state. I was able to pass the child state to the parent by linking the child's ...

The Mystery of jQuery Isotope Plugin: Why Can't I Add "display:none" Inline?

I'm currently in the process of integrating Isotope into my latest Wordpress theme. However, I've encountered an issue where it's not appearing on the page due to some external factor adding an inline style (display:none) to the main isotope ...

Using the spread operator in the console.log function is successful, but encountering issues when attempting to assign or return it in a

Currently facing an issue with a spread operator that's really getting on my nerves. Despite searching extensively, I haven't found a solution yet. Whenever I utilize console.log(...val), it displays the data flawlessly without any errors. Howev ...

Guide to using Ajax to load a partial in Ruby on Rails

Whenever a search is triggered, I have a partial that needs to be loaded. This partial can take a significant amount of time to load, so I would prefer it to be loaded via Ajax after the page has fully loaded to avoid potential timeouts. Currently, my app ...

converting code from JavaScript to Flask and then back to JavaScript, all within a single-page application

In order to make my single-page web app fully functional, I have completed the following tasks: Sent a json from .js to Flask (COMPLETED) Ran the input through a Python function called getString() and obtained a string output (COMPLET ...

Error in Cordova Android Compilation ("unable to locate Build Tools version 24.0.1")

I'm currently experiencing some difficulties while trying to compile my Cordova project on Android. Upon entering the command "cordova build Android", I encountered the following error message: FAILURE: Build failed with an exception. * What caused ...

I encountered a TS error warning about a possible null value, despite already confirming that the value

In line 5 of the script, TypeScript raises an issue regarding the possibility of gameInstanceContext.gameInstance being null. Interestingly, this concern is not present in line 3. Given that I have verified its existence on line 1, it is perplexing as to w ...

Assign a value to an element based on a specific attribute value

I'm working with the following element <input type="text" size="4" name="nightly" value="-1"> My goal is to update the value to 15.9 specifically when name="nightly" Here's what I've attempted so far: document.getElementsByName(&ap ...

Guide to sorting data by the status value within a JavaScript object?

I have a JavaScript object structured like this: { "3": { "id": 3, "first": "Lisa", "last": "Morgan", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bbd7d6d4c9dcdad5fbdcd6dad2d795d8d4d6">[email&# ...

Tips for effectively retrieving data from the server in Node.js

When attempting to retrieve data using /data with server-side fetch, I encountered the following errors: response.getCategory is not a function (()=>{ const url = "/data"; fetch(url) .then(response => { console ...

Google Analytics does not include e-commerce tracking capabilities

Testing out the e-commerce-tracking feature, I modified Google's standard-script to ensure its functionality: <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i ...

Monitor the true/false status of each element within an array and update their styles accordingly when they are considered active

Currently, I am attempting to modify the active style of an element within an array. As illustrated in the image below - once a day is selected, the styles are adjusted to include a border around it. https://i.stack.imgur.com/WpxuZ.png However, my challe ...

How to Use AJAX, jQuery, and JSON to Send an Array to PHP

I'm attempting to send an associative array through AJAX $.post to a PHP script. Below is the code I am using: var request = { action: "add", requestor: req_id, ... } var reqDetails = $("#request_details").val(); ...

Leverage Node.js modules to reassign variable values

My simplified JavaScript module simulates an eye pose. var pose = {}; var eye = {}; var left = {}; left.pitchPos = 37; left.yawPos = 47; exports.init = function () { eye.left = left; pose.eye = eye; return this; }; exports.eye = function (e ...

Execute the controller function with the value as a parameter

I encountered an issue while attempting to call a function in the c# controller and passing a value. The error message I received was: `'Unable to get property 'then' of undefined or null reference'. I also included the Driver Model but ...

The impact of a variable in a function with XMLHttpRequest

How does the XMLHttpReqeust variable impact the functionality of the following code snippets? function getHTTPObject() { if (typeof XMLHttpRequest == "undefined") { XMLHttpRequest = function () { try { return new Ac ...

Is there a way to adjust the label size for a material ui TextField component?

My TextField element is defined like this: <TextField id="standard-with-placeholder" label="First Name" className={classes.textField} margin="normal" /> It currently appears as shown in the image below: https://i.sstatic.net/aYi1a.png How ...

Choosing the Right Server Software for AngularJS Web Development

I'm seeking clarification on a particular concept: After being away from web development for around 3-4 years, I'm feeling lost as I try to get back into it and catch up with the latest technologies. In the past, I was accustomed to using JSP/P ...

Problem with $http.post() in Angular where Codeigniter is not able to receive data

I'm facing a peculiar issue with Codeigniter and Angular. My approach was to configure the controller in the following way: index is a simple Angular page with just one app and one controller get retrieves data from the database set saves data sent u ...

Creating a Class in REACT

Hello fellow coding enthusiasts, I am facing a minor issue. I am relatively new to REACT and Typescript, which is why I need some assistance with the following code implementation. I require the code to be transformed into a class for reusability purposes ...