Binding the same model variable to radio buttons and input-text - javascript

I would like manage with AngularJS UI which allows to pick one of the options (displayed as radio buttons group) or a custom value typed in a input-text.
It should look like:
http://jsbin.com/foyujali/7/edit
Here is the code that you can see also in the link below:
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.js"></script>
<div ng-app="tagsApp" ng-controller="TagsCtrl">
<input type="radio" id="conversion_type_sale" ng-model="tag.conversion_type" value="sale"/>
<label for=conversion_type_sale>Sale</label>
<input type="radio" id="conversion_type_lead" ng-model="tag.conversion_type" value="lead"/>
<label for=conversion_type_lead>Lead</label>
<input type="radio" id="conversion_type_custom" ng-model="tag.conversion_type" value="{{tag.conversion_type_custom_value}}"/>
<input type="text" placeholder="Custom" ng-model="tag.conversion_type_custom_value" id="conversion_type_custom_value"/>
<p>
The choosen conversion type is: <strong>{{tag.conversion_type}}</strong>
</p>
</div>
And JS:
angular.module('tagsApp', []).
controller('TagsCtrl', function ($scope) {
$scope.tag = {conversion_type: 'lead'};
});
I would prefer not to use ngChange directive so I just bind the value or ng-value (I tried both) to the model of the input-text. It doesn't work properly this way, but I suppose there is an elegant AngularJS solution. Any suggestions?
Thanks in advance!
P.S. Just to clarify - I want the following functionality: http://jsbin.com/foyujali/10/edit but I want to avoid using ngChange directive.

This is what you're looking for: http://jsfiddle.net/colares/shcv8e1h/2/
Explaning the behavior
By focusing on the text field, the radio on the left is selected and chosen value is updated regarding the value of the text field;
By focusing on radio on the left of the text field, the chosen value is updated according to what is in the text field as well;
By changing the value of the text field, the chosen value is also updated;
Finally, by focusing on any other label or radio, the custom value remains, while the chosen value is update regarding the selected option.
To do so, I had to use a few more things in custom option input:
ng-focus: when I click on the text field, it updates the chosen value regarding the text field;
ng-change: as I update the text field, the final value is also updated;
ng-model: to store the auxiliar variable customColor, which remains regardless of the selected value.
Remember, the ng-value is used to set the value of the radio (or an <option>) from a given expression when we select it. This makes the radio and input text "bound", because they have the same value.

You could use $scope.$watch and look for the change in your controller like so:
http://jsfiddle.net/2R6aN/
var app = angular.module('tagsApp',[]);
app.controller('TagsCtrl', function ($scope) {
$scope.tag = {conversion_type: 'lead'};
$scope.$watch('conversion_type_custom_value',function(new_val) {
if (new_val) {
$scope.tag.conversion_type = new_val;
}
});
});

$watch is best option. Also, Instead of using modelName in 1st parameter of $watch, you can create your own stuff(eg. watching length of input box) and do desired action on it with second parameter.

Related

One item select not working on radio buttons in AngularJS

I'm using AngularJS and filter option. When I select an item in radio buttons, its getting right data.
<input ng-click="filter = !filter" ng-value="!filter" ng-checked="filter" type="radio" ng-model="ctrl.filter[category]" />
But I need allow one select in radio buttons and its not working. What's the problem? Thanks.
DEMO
To properly work, radio inputs need a name attribute. It should be the same for all radio of the groupe.
You also need to change the ng-model of the radio to store its value in a single property.
<input ng-click="filter = !filter" ng-value="category" name="wineCategory" ng-checked="filter" type="radio" ng-model="ctrl.filter" />
Finally you need to adapt your filter methods.
All the inputs in the Radio box group must have only one reference to an ng-model which is typically the value of the input.
So, your input markup would be
<input value="{{category}}" type="radio" ng-model="ctrl.filterCategory" />
Where the value = category would be red, while or champagne.
Now likewise your filter function would change to use the ng-model like this
function filterByCategory(wine) {
return (self.filterCategory === wine.category || self.filterCategory === "") ? 'show':'hide';
}
Working demo here.
http://jsfiddle.net/nah42h1c/2/

AngularJS: Using ngRepeat and ngModel with a checkbox is causing all checkboxes to become ticked

My HTML:
<div class="panel-body">
<span ng-repeat="industry in ctrl.industryList">
<label>
<input type="checkbox" id="industry" ng-model="ctrl.oneIndustry" ng-change="ctrl.updateSelected(industry)">
{{industry}}
</label><br/>
</span>
</div>
I am iterating through an array of industries and displaying a checkbox. When the checkbox is ticked, it is stored into an array. If the checkbox is then unticked, I would like to remove it from the array:
My Controller code:
vm.updateSelected = function (industry) {
if (vm.oneIndustry) {
vm.industries.push(industry)
}
else{
vm.industries.pop(industry)
}}
The current problem is when a checkbox is clicked, All of the items in the list get ticked although only the once which is clicked is saved. On untick, the item is removed from the list and all checkboxes become unticked. How do I tick and untick only the specific tickbox?
You can't use the same static ng-model for multiple check boxes, you need to either use a dynamic ng-model or one assigned to a value in the repeated array. This is so that each check box has its own separate model.
You can do this in multiple ways:
Add to your repeated array so that it has a value in each object in the array that says whether that object is selected or not. To do this you would assign it like ng-model="industry.isSelected".
Have a separate object that stores the bool for whether each array object is selected. To do this you would assign it like so ng-model="selection.industryIds[industry.id]"
In your case the best option is likely the first one, you would also need to change the if statement to the following though:
vm.updateSelected = function (industry) {
if (industry.isSelected) {
vm.industries.push(industry)
}
else{
vm.industries.pop(industry)
}}
ngModel helper
ngModel, input shoulde be string. Assignable AngularJS expression to data-bind to.
The name of AngularJS expression should be different.
<input type="checkbox" id="industry-one" ng-model="ctrl.oneIndustry"/>
<input type="checkbox" id="industry-two" ng-model="ctrl.twoIndustry"/>

How to Deselect All Radio Inputs?

I am using angular and have a radio input like this (in a form, if it matters):
<input type="radio"
name="inputName"
id="someId"
data-ng-value=true <!-- This select "true" for my ng-model when clicked-->
ng-model = "nameOfMyVarIn$scope"
ng-change = "thisRunsWhenSelectionIsmade(true)"
required></input>
I want to clear this input. Clearing the variable bound to ng-model clears the variable, but not the checkbox. I can't find how to clear the radio button itself in the docs or in random articles - it stays selected. I made a quick copy of the example from the docs and added $scope.clearSelection - the goal is to have this function de-select the selected input. In the real application I have other inputs in the form, so I can't just clear the whole form.
Plnkr
Using your Plnkr, I've set color to null and it cleared the value. Is this what you want?
$scope.clearSelection = function(){
$scope.color = null;
}
Here is the updated Plnkr

Knockout Js Radio Bindings not setting Value

Here is the documentation I'm looking at : Example Adding Radio Buttons
It says:
KO will set the element to be checked if and only if the parameter value equals the radio button node’s value attribute
Which I have done in this: jsfiddle
self.radioValue = ko.observable(1);
and the HTML:
<input type="radio" name="teloremail" value="1" data-bind="checked: radioValue" />
For me, this doesn't automatically set the radio to checked
Any reason for this?
The type of the radio button node’s value attribute is string, so you need to store the value as string also in your observable:
self.radioValue = ko.observable("1");
Demo JSFiddle.
The example also uses a string: "almond".

jQuery - Change name of an input field by using value of another input field filled at the same time

I'm working on a dynamic form where you can add or delete fields, Here you can find the fiddle
The first button you find is Add Metric. From this the code generates:
Input Field Metric
Button Add Tag
Inside this field a user can add a tag with the button Add Tag, generated when you click add Metric. When you click Add Tag button, two fields are generated:
Input Field Id
Input Field Value
The Html code that I need to generate in order to serialize the entire form (this is not however the question point) will result like this:
<input type="text" name="metrics[0][name]" value="Text 0"> // Metric
<input type="text" id="TagId0" name=" "> //Tag Id
<input type="text" id="TagValue" name="metrics[0][tags][][0]">
Problem:
I need that (when I fill the field with id="TagId0") the value I select will go immediately to the field name with id="TagValue". This field must result like this:
Consider I write on TagId0 the word "hello", field will become:
<input type="text" id="TagValue" name="metrics[0][tags][hello][0]">
How, if it's possible, it can be done?
Thanks
You can use the change method to detect a change in the fields value. Then use the attr method to change the name. Hope I understood correctly. Here is the modified JSFIDDLE.
$(document).on('change', '#InputsWrapper .inputID', function(){
thisVal = $(this).val();
thisName = $(this).siblings('.inputVal').attr('name');
newName = thisName.replace('[tags][', '[tags][' + thisVal);
$(this).siblings('.inputVal').attr('name', newName);
});
Don't forget to press enter after change the field value :)
Edit: I also added two classes to the fields you are appending. .inputID and .inputVal. I hope this helps!
you can write id of field something like TagId-0 and some common class like tagfield,so that u can split the value to get the index an then access it using the class
$(".tagfield").keypress(function() {
var id=parseInt($(this).attr("id").split("-"));
$(this).siblings().attr("name","metrics["+id+"][tags]["+$(this).val()+"][0]");
});

Categories