how to make array using angularjs? - javascript

i have list of subjects with checkbox.when user submit selected subjects i am getting properly but i need to make like this if user selected 3subjects(Tamil,Science,English) i want to declare like this var data = {"Subject" :[{subject0:Tamil,subject1:Science,subject3:English}]} someone help me out how to make . i have enclosed my html and controller
.controller('TestController', ['$scope','$http','$window','$location', function($scope,$http,$window,$location,$stateProvider)
{
var serverData = ["Tamil", "Science", "English","computer"];
$scope.items = [];
for (var i = 0; i < serverData.length; i++) {
var modal = {
name: serverData[i],
selected: false
};
$scope.items.push(modal);
}
$scope.submit = function()
{
var checkedItems = [];
for (var i = 0; i < $scope.items.length; i++) {
if ($scope.items[i].selected)
{
checkedItems.push($scope.items[i].name);
}
}
console.log(checkedItems);
//Expectation:
//var data = {
//"Subject" :[{subject0:Tamil,subject1:Science,subject3:English}]
//}
}]);
}
<div ng-controller="TestController">
<ul ng-repeat="item in items">
<li class="item item-checkbox">
<label class="checkbox checkbox-energized">
<input type="checkbox" ng-model="item.selected" >
</label>
{{item.name}}
</li>
</ul>
<input type="button" name="submit" value="submit" ng-click="submit()"/>
</div>

Try below :
$scope.submit = function()
{
var checkedItems = [], data = [];
for (var i = 0; i < $scope.items.length; i++) {
if ($scope.items[i].selected)
checkedItems.push("Subject"+i, $scope.items[i].name);
}
data.push("Subject", checkedItems);
}

You could simply do like this.
$scope.submit = function() {
var checkedItems = [], data = {};
for (var i = 0; i < $scope.items.length; i++) {
if ($scope.items[i].selected)
checkedItems["Subject" + i] = $scope.items[i].name;
}
data["Subject"] = checkedItems;
console.log(data); // {"Subject" :[{subject0:Tamil,subject1:Science,subject3:English}]}
}

I make it bit more angular way
<div ng-controller="ControllerZero">
{{data.Subject}}
<ul ng-repeat="item in serverData">
<li class="item item-checkbox">
<label class="checkbox checkbox-energized">
<input type="checkbox" ng-model="$parent.subject[$index]">
</label>{{item}}</li>
</ul>
<input type="button" ng-click="showData()" value="show data">
</div>
javascript :
var myModule = angular.module('myModule', []);
function ControllerZero($scope, Timer) {
$scope.serverData = ["Tamil", "Science", "English", "computer"];
$scope.subject = [];
$scope.data = {'Subject' : [{}]};
$scope.showData = function() {
var count = 0;
$scope.data.Subject[0] = {};
angular.forEach($scope.subject, function(value, key) {
if(value === true) {
$scope.data.Subject[0]['subject' + count] = $scope.serverData[key];
count++;
}
})
}
}
ControllerZero.$inject = ['$scope'];
fiddle link : http://fiddle.jshell.net/55zjjyhk/
or you can make it become realtime by put $watch, but seems that unnecessary.

Related

ngDupes error with the checkboxes AngularJs

I'm trying to fix my ngdupes error with the checkbox selection. I don't know what's going wrong. Can someone please help? Here is my code:
$scope.GetMultiCheckBox = function GetMultiCheckBox(CheckBoxs) {
var idx = $scope.selectedfunction.indexOf(CheckBoxs);
if (idx > -1) {
$scope.selectedfunction.splice(idx, 1);
}
else {
$scope.selectedfunction.push(CheckBoxs);
}
};
$scope.FilterValueByFunction = function (FunctionVal) {
$scope.Lv7 = [];
if (!$scope.selectedfunction.length == '') {
for (var i = 0; i < $scope.LoadAllData.length; i++) {
for (var j = 0; j < $scope.selectedfunction.length; j++) {
if ($scope.LoadAllData[i].Business_x0020_Checkbox.results.toString().match($scope.selectedfunction[j])) {
$scope.Lv7.push($scope.LoadAllData[i]);
}
}
}
} else {
for (var i = 0; i < $scope.LoadAllData.length; i++) {
$scope.Lv7.push($scope.LoadAllData[i]);
}
}
};
Here is my HTML code for checkboxes:
<ul><li ng-repeat="item in functions">
<input id="{{item}}" type="checkbox" value="{{item}}" ng-disabled="Site.length == 0"
ng-checked="selectedFunction.indexOf(item) > -1"
ng-click="GetMultiCheckBox(item); FilterValueByFunction(item);" autocomplete="off"/></li></ul>
This is the code for the whole data getting filtered based on choices:
<div ng-repeat="item in Lv8|orderBy: 'Category'| filter: SiteFilter
|groupBy: 'Category' | filter: searchBox">
<div id="grad1" ng-show="item.Category_CHANGED">{{item.Category}}
</div>
Thanks!

how to checked only one checkbox in ng-repeat checkbox using angularjs?

when i go to page i need always checked somecheck boxes like software or harware.if any one selected then only submit button will visible.if nothing is selected submit button should disable and alert should come please select some services
function Test1Controller($scope) {
var storeid = window.localStorage.getItem("storeid");
var serverData = ["software", "hardware", "Accessories"];
$scope.items = [];
for (var i = 0; i < serverData.length; i++) {
var modal = {
name: serverData[i],
selected: i === 0 ? true : false,
};
$scope.items.push(modal);
}
$scope.check = function() {
var checkedItems = [];
for (var i = 0; i < $scope.items.length; i++) {
if ($scope.items[i].selected) {
checkedItems.push($scope.items[i].name);
}
}
console.log(checkedItems);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
<div ng-app>
<div ng-controller="Test1Controller">
<div ng-repeat="item in items">
<input type="checkbox" ng-model="item.selected" />{{item.name}}
</div>
<input type="button" name="submit" value="submit" ng-click="check()" />
</div>
</div>
function Test1Controller($scope) {
var storeid = window.localStorage.getItem("storeid");
var serverData = ["software", "hardware", "Accessories"];
$scope.items = [];
for (var i = 0; i < serverData.length; i++) {
var selectVal = false;
if(serverData[i] === "hardware"){
selectVal = true;
}
var modal = {
name: serverData[i],
selected: selectVal
};
$scope.items.push(modal);
}
}

how to display checked values in checkbox using angular array?

I've already accomplished selecting htc in home page and coming to another page. Now I want to display whether the selected store value and severdata match (in this case I need to show true). During the on submit event, I want to pass all selected values. I have tried the code below, but its not working for me.
$scope.Selctedstores =window.localStorage.getItem("selectedservices");
console.log($scope.Selctedstores);
//console i am getting htc
var serverData = ["Nokia", "Htc", "Samsung"];
$scope.items = [];
for (var i = 0; i < serverData.length; i++)
{
var modal = {
name: serverData[i],
selected: false
};
$scope.items.push(modal);
}
$scope.check = function()
{
var checkedItems = [];
for (var i = 0; i < $scope.items.length; i++) {
if ($scope.items[i].selected) {
checkedItems.push($scope.items[i].name);
}
}
console.log(checkedItems);
}
html
<div ng-controller="Test1Controller">
<div ng-repeat="item in items">
<input type="checkbox" ng-model="item.selected" /> {{item.name}}
</div>
<input type="button" name="submit" value="submit" ng-click="check()" />
</div>
Before pushing to items array check whether the item is present already in the selected store. If so, then assign selected as true. Hope this helps. Let me know if you have any problem
check updated fiddle
function TodoCtrl($scope) {
var serverData = ["Nokia", "Htc", "Samsung"];
var selectedStore = ["Htc"]
$scope.items = [];
for (var i = 0; i < serverData.length; i++)
{
var modal = {
name: serverData[i],
selected: false
};
if (selectedStore.indexOf(serverData[i]) >= 0) {
modal.selected = true;
}
$scope.items.push(modal);
}
$scope.check = function()
{
var checkedItems = [];
for (var i = 0; i < $scope.items.length; i++) {
if ($scope.items[i].selected) {
checkedItems.push($scope.items[i].name);
}
}
console.log(checkedItems);
}
}
Try
for(var i=0;i<serverData.length;i++)
{
var modal = {
name:serverData[i],
selected:($scope.Selctedstores !== null && $scope.Selctedstores.indexOf(serverData[i]) > -1) ? true : false
};

Using jQuery to dynamically create checkboxes based on multiple attributes from div

I would like for jQuery to dyanmically create a list of checkboxes based on the class/data present in divs. Essentially these checkboxes will filter through the products so that clicking a checkbox will show the products containing that tag in their div while avoiding any duplicate checkboxes.
Sample:
<div class="Shoes" data-size="Small" data-color="Black">
<h3>Nike</h3>
</div>
<div class="Belts" data-size="Medium" data-color="Black">
<h3>Belt</h3>
</div>
<div class="Shirt" data-size="Large" data-color="Blue">
<h3>Polo</h3>
</div>
<div class="Socks" data-size="Small" data-color="White">
<h3>Generic Socks</h3>
</div>
Expected output
Class Type
Shoes
Belts
Shirt
Socks
Size
Small
Medium
Large
Color
Black
White
Blue
Each checkbox needs to be able to hide/show the item.
JsFIDDLE
The code I have so far is from searching around/previous answers, however it is only creating 1 checkbox type which is for "class" and not creating multiple ones.
Try
jQuery(function ($) {
function createCheckboxes($els, attr) {
var props = {};
$els.each(function () {
props[$(this).attr(attr)] = true;
});
return $.map(props, function (val, key) {
var $chk = $('<input />', {
type: 'checkbox',
value: key
})
return $('<label />', {
text: key
}).append($chk)
})
}
$('span').append(createCheckboxes($('div'), 'class'))
$('span').append(createCheckboxes($('div'), 'data-size'))
$('span').append(createCheckboxes($('div'), 'data-color'))
});
Demo: Fiddle
Try this http://jsfiddle.net/LzmTA/1/
HTML
<div class="Shoes" data-size="Small" data-color="Black">
<h3>Nike</h3>
</div>
<div class="Belts" data-size="Medium" data-color="Black">
<h3>Belt</h3>
</div>
<div class="Shirt" data-size="Large" data-color="Blue">
<h3>Polo</h3>
</div>
<div class="Socks" data-size="Small" data-color="White">
<h3>Generic Socks</h3>
</div>
Javascript
$(document).ready(function(){
var goods = {};
var divs = $('div');
for(var i = 0; i < divs.length; i++){
var attributes = divs[i].attributes;
var item = {};
for(var j = 0; j < attributes.length; j++){
var attrName = attributes[j].name;
if(!goods[attrName]){
goods[attrName] = {};
}
goods[attrName][attributes[j].value] = 1;
}
}
printAttributes(goods);
console.log(goods);
});
function printAttributes(goods){
for(var group in goods){
var groupTitle = $('<h3>').text(group);
$('span').append(groupTitle);
for(var item in goods[group]){
console.log(item);
var sp = $('<label>').text(item);
var chk = $('<input>').attr('type', 'checkbox').attr('value', item).attr('attr', group);
chk.bind('change', function(){
filterGoods();
});
$('span').append(chk).append(sp);
}
}
}
function filterGoods(){
var separator = '|';
var chks = $('input[type=checkbox]:checked');
var filter = [];
//get filter
for(var i = 0; i < chks.length; i++){
var item = $(chks[i]).attr('attr') + separator + $(chks[i]).val();
filter.push(item);
}
//do filter
var hasAttr = false;
var divs = $('div');
for(var i = 0; i < divs.length; i++){
hasAttr = false;
for(var j = 0; j < filter.length; j++){
var filterParts = filter[j].split(separator);
if($(divs[i]).attr(filterParts[0]) == filterParts[1]){
hasAttr = true;
continue;
}
}
hasAttr ? $(divs[i]).show() : $(divs[i]).hide();
}
console.log(filter);
}

Why the script is not running on all input elements?

I am using this script to hide the default value of input elements on my page:
<script>
var active_color = '#000'; // Colour of user provided text
var inactive_color = '#ccc'; // Colour of default text
window.onload = formDefaultValues;
function formDefaultValues() {
var fields = getElementsByClassName(document, "input", "default-value");
if (!fields) {
return;
}
var default_values = new Array();
for (var i = 0; i < fields.length; i++) {
fields[i].style.color = inactive_color;
if (!default_values[fields[i].id]) {
default_values[fields[i].id] = fields[i].value;
}
fields[i].onfocus = function() {
if (this.value == default_values[this.id]) {
this.value = '';
this.style.color = active_color;
}
this.onblur = function() {
if (this.value == '') {
this.style.color = inactive_color;
this.value = default_values[this.id];
}
}
}
}
}
function getElementsByClassName(oElm, strTagName, strClassName){
var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
var arrReturnElements = new Array();
strClassName = strClassName.replace(/\-/g, "\\-");
var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
var oElement;
for (var i = 0; i < arrElements.length; i++) {
oElement = arrElements[i];
if (oRegExp.test(oElement.className)) {
arrReturnElements.push(oElement);
}
}
return (arrReturnElements);
}
</script>
I use this code to loop on input elements that have the class "default-value" and fire the action on them. It's really working on some elements but not others? What might be going wrong?
Thanks in advance
This worked for me..
<html>
<script>
function ViewAllElements() {
var fe = document.forms['myForm'].elements;
alert(fe.length);
for(var i = 0; i < fe.length; i++)
{
alert(fe[i].value);
}
var ebc = getElementsByClassName(document, "input", "fieldA");
alert(ebc.length);
for(var j = 0; j < ebc.length; j++)
{
alert(ebc[j].value);
}
}
function getElementsByClassName(oElm, strTagName, strClassName){
var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
var arrReturnElements = new Array();
strClassName = strClassName.replace(/\-/g, "\\-");
var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
var oElement;
for (var i = 0; i < arrElements.length; i++) {
oElement = arrElements[i];
if (oRegExp.test(oElement.className)) {
arrReturnElements.push(oElement);
}
}
return (arrReturnElements);
}
</script>
<body>
<form id="myForm" name="myForm">
<input class="fieldA" id="field1" name="field1" value="field1value">
<input class="fieldA" id="field2" name="field2" value="field2value">
<input class="fieldA" id="field3" name="field3" value="field3value">
<input class="fieldB" id="field4" name="field4" value="field4value">
<input class="fieldB" id="field5" name="field5" value="field5value">
<input class="fieldB" id="field6" name="field6" value="field6value">
<input type="button" onClick="ViewAllElements();" value="View">
</form>
</body>
</html>

Categories