I have this input:
<input type="checkbox" ng-model="area.id" data-id="{{area.id}}"/>
and some ng-click action above, I'm trying to collect all selected checkboxes id's but after check action data-id attribute turns to true/false, why?
Function from controller:
collectSelectedAreas($event) {
let selectedArea = $event.currentTarget.querySelectorAll('input:checked');
let areaIds = [];
[selectedArea].forEach((el) => {
console.log(el.attributes['data-id'].value);
});
}
Option 1:
You could select another property to track the checkbox value (true/false) like this:
<input type="checkbox" ng-model="area.selected" data-id="{{area.id}}"/>
area.selected = true in case of checkbox is selected
Then in your function, iterate over your area's Array, lets suppose you have an arrayOfAreas, the same array that you are iterating in your ng-repeat
collectSelectedAreas() {
let areaIds = [];
arrayOfAreas.forEach((el) => {
if (el.selected){
areasId.push(el);//Add selected element to array
console.log(el.id);
}
});
}
Option 2:
<input type="checkbox" ng-model="area.selected" data-id="{{area.id}}" ng-true-value="area.id" ng-false-value="'NO'"/>
It means that when checkbox is checked area.selected will take the area.id value, otherwise the string 'NO';
You need not to access DOM for getting selected checkbox. You can check this by checking the model value area.id . It will contain true for if checkbox is selected. Then you can traverse through area object, where you can get key to identified the id of selected checkbox.For Eg.
<input type="checkbox" ng-model="area.id" />
where
$scope.area.id==true if checkbox is selected.
Related
I have an array of objects
and i have a dropdown box with these names in with a text box to show the value that is inside the object that is selected
I have the input box set to
<input type="text" class="form-control" ng-model="o.boxes.box1[0]">
is there a way to set "box1[0]" to the selected dropdown value? the dropdown box is selectedNumber. I tried ng-model="o.boxes.{{selectedNumber}}[0]" but this didnt work.
ng-model="o.boxes.{{selectedNumber}}[0]"
You can do what you want with just a lit refactor of your code.
The best way to do this should be: update input ng-model reference with the current selection of your dropdown.
In your Controller:
$scope.boxes = {
box1: [],
box2: [],
box3: []
}
$scope.selectedBoxModel = null;
$scope.onDropdownSelection = function (selectedBox) {
$scope.selectedBoxModel = selectedBox;
}
And in your template on your input you will reference the ng-model with the selected box:
<input type="text" class="form-control" ng-model="selectedBoxModel[0]">
Try giving run time expression evaluation as shown below.
ng-model="o.boxes[{{selectedNumber}}][0]"
I have this AngularJS code
var app = angular.module('testApp', []);
app.controller('testController', function ($scope) {
$scope.MyTypes = [
{ name: 'Option1', value: 100 },
{ name: 'Option2', value: 101 },
{ name: 'Other', value: 102 }
];
$scope.SelectedType = $scope.MyTypes[0];
$scope.SelectedValue = $scope.MyTypes[0].value;
$scope.onChange = function () {
$scope.SelectedValue = $scope.SelectedType.value;
}
});
with this HTML
<div ng-app="testApp">
<div ng-controller="testController">
<select ng-model="SelectedType" ng-options="ft.name for ft in MyTypes" ng-change="onChange()"></select>
<input type="text" value="{{SelectedValue}}"/>
</div>
</div>
This displays the value in the input box, taken from the selected item of the Select list as when items are selected from the list.
This code works fine until user types something in to the input textbox, then the binding is lost and the text box value does not get updated.
Is this a normal behavior in AngularJS?. How to overcome this and get it working (replace the entered text with the value from the select list when different item is selcted) even after the user types something in?
Demo Fiddle
To get the desired effect you should bind the input to the SelectedValue using ng-model rather than having an interpolated value in the value attribute:
<input type='text' ng-model='SelectedValue' />
The key to the behaviour you're seeing is that the value attribute on the input is the initial value of the control not the value of the input.
As soon as you enter text into the input field, whatever is in the value attribute is no longer relevant. The value attribute will contain the new value but it will not affect the value in the control (have a look in a DOM inspector).
It's not normal behavior, You need to bind your text box. your are just setting the value in you text box but not binding like this
<input type="text" ng-model="SelectedValue" value="{{SelectedValue}}"/>
Here is the updated code.enter link description here
Demo Fiddle
I am wondering if there is a way to reset a radio to it's originally selected option. I know of defaultValue for inputs but is there a way to make it so that I can reset the radios back to their originally selected value on page load?
I am not wanting to simply unselect all radios. I am trying to put them back to their originally selected value.
Thanks for any info.
Yes, radio inputs do have defaultValue property, but what you are looking for is the defaultChecked property:
$('input[type=radio]').prop('checked', function() {
return this.defaultChecked;
});
That being said, if you want to reset the form you can use the reset method of the HTMLFormElement object:
$('#formElement').get(0).reset();
I think you want this
<form action="">
<input type="radio" name="gender" value="male" checked="true"/>Male
<input type="radio" name="gender" value="female"/>Female
<input type="reset" value="reset"/>
</form>
Any time you will reset the form, the male radio button will be selected.
I will rather make a jQuery plugin like this:
$.fn.defaultVal = function (checked) {
if(checked === true || checked === false) {
$(this).attr("data-default", checked);
return;
}
if(!$(this).attr("data-default")) {
console.log("No default value assigned!");
return;
}
return $(this).attr("data-default");
}
JSFIDDLE LINK UPDATE
Working Demo is here: JSFIDDLE
I have a function where I get an error saying "length" is null, I then did an alert to see the value and length and I see that the value is coming back in the loop, sometimes it has a String value and sometimes it has a number (eg. SUIT and then 8), but for some reason the length is showing as undefined? The radioobj variable takes radio button values that are coming in from the form input.
function getRadioValue(radioobj) {
radiovalue = "";
for (i=0, n=radioobj.length; i<n; i++) {
if (radioobj[i].checked) {
radiovalue = radioobj[i].value;
break;
}
}
if (!radiovalue) { return 0; }
else { return radiovalue; }
}
The way the code is written, it appears to be looking to take in a group of radio buttons and looping through them to find the one that is checked. To do that, the input MUST be a collection of radio buttons . . . passing an individual reference to a radio button will not work (and will give an undefined value for radioobj.length). Example:
HTML
<fieldset id="radioVals">
<input type="radio" name="radioVals" id="val0" value="">Pick an value . . .</input>
<input type="radio" name="radioVals" id="val1" value="Value1">Value 1</input>
<input type="radio" name="radioVals" id="val2" value="Value1">Value 2</input>
</fieldset>
Given this group, if you were to pass in a reference to any of the individual radio buttons (e.g., using document.getElementById), you will get and error, because what is returned by that method is the reference to an individual element.
var radioOption = document.getElementById("val0");
window.console.log(radioOption.length); // will log "undefined"
However, if you pass in an array of radio button elements (e.g., using .children), you can use the for loop, because the array will have a length.
var radioOptions = document.getElementById("radioVals").children;
window.console.log(radioOptions.length); // will log "3"
From what you are describing, it sounds like the code is using the first approach, rather than the second. There are certainly ways of doing this check with individual radio buttons, but that is not how this code has been set up.
You can get collection of radios with the same id easily.
Use for it document.forms['form_id']['radio_id']:
<form id="form_id">
<input type="radio" name="radio_name" id="radio_id" value="Value1" />Value 1
<input type="radio" name="radio_name" id="radio_id" value="Value2" />Value 2
<input type="radio" name="radio_name" id="radio_id" value="Value3" />Value 3
</form>
var radio_list = document.forms['form_id']['radio_id'];
alert(radio_list.lengh) // will "3"
how can i create a condition for multiple checkbox!
Input Field ID =" INsrvOtr "
CheckBox ID = "INsrv"
let's say that the that the user has two options,either put a value on the input field or choose any value from the checkbox but he can only choose "ONE" of the two options
Checkbox:
<input id="INsrv" name="INopt" type="checkbox" value="1" />1<br>
Input field:
<input id="OUTsrvOtr" name="OUToptOtr" type="text" value="" onblur="valINP()"/><br><br>
if the user inputs a value in the input field this will happen
if "input field" is not empty, class of all the "checkbox" will not contain a value.
<script>
function valINP(){
$("#INsrv1").prop('class','text')
$("#INsrvOtr").prop('class','validate[required] text-input text')
}
}
</script>
or if the user chooses to check the checkbox this will happen
and if the "checkbox" is not selected,class of "input field" will not contain a value.
<script>
$(document).ready(function() {
$("input[name$='INopt']").click(function() {
$("#INsrv1").prop('class','validate[minCheckbox[1]] checkbox text')
$("#INsrvOtr").prop('class','text')
});
});
</script>
or if both is not selected
the script will contain this two:
$("#INsrv").prop('class','validate[minCheckbox[1]] checkbox text')
$("#INsrvOtr").prop('class','validate[required] text-input text')
try optimize your code, some useful optimization for selecting controls
http://api.jquery.com/category/selectors/ or http://api.jquery.com/attribute-contains-prefix-selector/
using some thing like
$("#id|="INsrv"]').prop('class','')
sorry if the syntax goes wrong.
// Use this for INsrv([0-9]+)
$('[id^="INsrv"][id!="INsrvOtr"]').each(function() {
});
// Or if you only want to call `prop`
$('[id^="INsrv"][id!="INsrvOtr"]').prop('yourprop', '');
Then you can just call $('#INsrvOtr') separately.