Dynamic angular models? - javascript

Okay, so I am building a fake dish builder for a restraunt. I have a form that includes everything you need to build it, and the only thing I am having trouble with is the ingredient list. Here is my HTML:
<div class="icheckbox" ng-repeat="ing in ingredientList">
{{ing}}
<input type="checkbox" name="{{ing}}" ng-click="addIngredient(ing)"/>
<input type="number" name="more" ng-model="ings.ing.more" placeholder="price for extra"/>
<input type="number" name="less" ng-model="ings.ing.less" placeholder="price for less/none"/>
</div>
and here is the (relevent) JS:
$scope.ings = {};
$scope.ingredientList = ['lettuce', 'tomatoe', 'steak', 'pulled pork', 'green onion', 'red onion', 'mozarella', 'cheddar', 'bacon bits', 'chicken'];
$scope.addIngredient = function(which){
$scope.ings[which] = which;
}
$scope.makeItem = function(item){
item.ingredients = $scope.ings;
console.log(item);
ItemService.createItem(item)
.then(handleRes, handleRes);
}
As I'm sure you guessed, when I am trying to check a box for a specific ingredient and add the price modifiers for more or less of that specific ingredient, it modifies the price for all ingredients in the list. E.g., I can't have individual modifiers because of the model. I know this is a problem with the model, but how can I rewrite my code to accomplish what I'm doing?
for those reading this after the correct answer has been chosen, see the fiddle located here to see a more accurate HTML of what I was working with. By the way, the fiddle doesn't entirely work (for reasons I don't know, but I rarely use JSFiddle), but it is super easy to understand what I was trying to do if you see it I think. http://jsfiddle.net/Lrpjwyrg/13/

i a bit change your fiddle:
first, use ng-model="ings[ing].more" and ng-model="ings[ing].less".
second, save object in ings array instead of just string
$scope.addIngredient = function(which) {
$scope.ings[which] = {
name: which
};
}
angular.module('CpCtrl', []).controller('ControlPanelCtrl', [
'$scope',
function($scope) {
$scope.message = '';
$scope.inglist = ['lettuce', 'tomatoe', 'steak', 'pulled pork', 'green onion', 'red onion', 'mozarella', 'cheddar', 'bacon bits', 'chicken'];
$scope.sauceList = ['bbq', 'ranch', 'nacho cheese', 'yum sauce'];
$scope.ings = {};
$scope.addIngredient = function(which) {
$scope.ings[which] = {
name: which
};
}
$scope.makeItem = function(item) {
item.ingredients = $scope.ings;
console.log(item);
}
}
]);
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="container-fluid text-center" ng-app="CpCtrl" ng-controller="ControlPanelCtrl">
<div class="row">
<div class="page-title text-center">
<h3> Welcome</h3>
</div>
</div>
<div class="row">
<div class="jumbotron">
<h2> Make Item </h2>
<form>
<div class="form-group">
<label for="itemname">Item Name</label>
<input class="form-control" type="text" ng-model="item.itemname" id="itemname" />
</div>
<div class="form-group">
<label for="itemdescription">Item Description</label>
<textarea class="form-control" ng-model="item.itemdescription" id="itemdescription"></textarea>
</div>
<!-- pizza, sub or spud -->
<label>
<div class="icheckbox_square-green">
<input type="checkbox" name="pizza" ng-model="item.pizza" ng-click="setBase()" />Pizza
</div>
</label>
<label>
<div class="icheckbox">
<input type="checkbox" name="sub" ng-model="item.sub" ng-click="setBase()" />Sub
</div>
</label>
<label>
<div class="icheckbox">
<input type="checkbox" name="spud" ng-model="item.spud" ng-click="setBase()" />Spud
</div>
</label>
<!-- end -->
<!-- prices -->
<div class="form-group">
<label for="spud-price" ng-if="item.spud">Spud Price</label>
<input class="form-control" type="number" name="spud-price" ng-if="item.spud" id="spud-price" ng-model="item.price.spud" />
</div>
<div class="form-group">
<label for="pizza-price" ng-if="item.pizza">Pizza Price</label>
<input class="form-control" type="number" name="pizza-price" ng-if="item.pizza" ng-model="item.price.pizza" />
</div>
<div class="form-group">
<label for="sub-price" ng-if="item.sub">Sub Price</label>
<input class="form-control" type="number" name="sub-price" ng-if="item.sub" ng-model="item.price.sub" />
</div>
<!-- end -->
<!-- ingredients -->
<div ng-repeat="ing in inglist">
{{ing}}
<input type="checkbox" name="{{ing}}" ng-click="addIngredient(ing)" />
<input type="number" name="more" ng-model="ings[ing].more" placeholder="price for extra" />
<input type="number" name="less" ng-model="ings[ing].less" placeholder="price for less/none" />
</div>
<!-- end -->
<!-- picture -->
<div class="form-group">
<label for="picture">Add Picture(s)</label>
<input type="file" name="picture" />
</div>
<!-- end -->
<a class="btn btn-primary" ng-click="makeItem(item)">Create</a>
</form>
</div>
</div>
<!-- end item creation -->

I don't know if this is the right answer. But i think it is close to what you want.
angular.module('app', [])
.controller('cntrl', function ($scope) {
$scope.ingredientList = [{
name: 'lettuce',
count: 0,
price: 23,
selected: false
}, {
name: 'tomatoe',
count: 0,
price: 87,
selected: false
}, {
name: 'steak',
count: 0,
price: 98,
selected: false
}, {
name: 'pulled pork',
count: 0,
price: 292,
selected: false
}];
$scope.setItOne = function (idx) {
if ($scope.ingredientList[idx].count < 1) {
$scope.ingredientList[idx].count = 1;
}
updateSelectedingredients();
};
function updateSelectedingredients() {
$scope.selectedingredients = $scope.ingredientList.filter(function (item) {
return item.selected;
});
}
$scope.getTotal = function(){
var total = 0;
( $scope.selectedingredients || []).forEach(function(item){
total = total + item.count * item.price;
});
return total;
};
$scope.makeItem = function () {
alert(JSON.stringify($scope.selectedingredients));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="cntrl">
<div class="icheckbox" ng-repeat="ing in ingredientList">{{ing.name}}
<input type="checkbox" name="{{ing}}" ng-model="ing.selected" ng-change="setItOne($index)" />
<button ng-click="ing.count = ing.count + 1">Up</button>
<button ng-click="ing.count = ing.count - 1" ng-disabled="ing.count < 1">Down</button>
| {{ing.count}} x {{ing.price | currency}} = {{ing.count * ing.price | currency}}
</div>
<hr/>
<div>Selected items
<ul>
<li ng-repeat="item in selectedingredients">{{item.name }} x {{item.count}} -> {{item.count}} x {{item.price | currency}} = {{item.count * item.price| currency}}</li>
</ul>
<b>Total: {{ getTotal() | currency}}</b>
</div>
<button ng-click="makeItem()">Make Item</button>
</div>
</div>

Related

JavaScript: Unable to set logic for searching

I'm working on a movie website, where I m stuck on setting search filter for user as I want that if user click on particular genres so it display that particular genre movies but I was unable to set logic for this :-
here is JavaScript code :-
/jshint esversion:6
const selected = document.querySelector(".selected");
const optionsContainer = document.querySelector(".option-container");
const optionList = document.querySelectorAll(".option");
selected.addEventListener("click", clickable);
function clickable() {
optionsContainer.classList.toggle("active");
}
optionList.forEach(o => {
o.addEventListener("click", function() {
selected.innerHTML = o.querySelector("label").innerHTML;
optionsContainer.classList.remove("active");
});
});
// search bar
const searchBar = document.forms['search-books'].querySelector('input');
searchBar.addEventListener("keyup", function(e) {
const term = e.target.value.toLowerCase();
const books = document.getElementsByTagName('h4');
Array.from(books).forEach(function(book) {
const title = book.textContent;
if (title.toLowerCase().indexOf(term) != -1) {
book.parentElement.parentElement.style.display = 'flex';
} else {
book.parentElement.parentElement.style.display = 'none'
}
});
});
const allMovies = document.querySelector("#all");
allMovies.addEventListener("click", function () {
var all = document.querySelectorAll(".allMovie");
all.forEach(function (a) {
a.classList.toggle('active');
});
});
const actionMovie = document.querySelector("#action");
actionMovie.addEventListener("click", function () {
var movies = document.querySelectorAll(".allMovie");
movies.forEach(function (f) {
if (f.classList.contains("actionMovie")) {
f.classList.toggle('active');
}else {
f.classList.toggle('inactive');
}
});
});
const dramaMovie = document.querySelector("#drama");
actionMovie.addEventListener("click", function () {
var movies = document.querySelectorAll(".allMovie");
movies.forEach(function (f) {
if (f.classList.contains("dramaMovie")) {
f.classList.toggle('active');
}else {
f.classList.toggle('inactive');
}
});
});
Html code:
<section class="search-section">
<div class="select-box">
<div class="option-container">
<div class="option" id="all">
<input type="radio" class="radio" name="category" value="All">
<label for="all">All</label>
</div>
<div class="option" id="action">
<input type="radio" class="radio" name="category" title="actionmovie" value="Action">
<label for="action">Action</label>
</div>
<div class="option" id="Drama">
<input type="radio" class="radio" id="drama" name="category" value="Drama">
<label for="drama">Drama</label>
</div>
<div class="option" id="Sci-fi">
<input type="radio" class="radio" id="sci-fi" name="category" value="Sci-fi">
<label for="sci-fi">Sci-fi</label>
</div>
</div>
<div class="selected">
<h2>Genre</h2>
</div>
</div>
<form class="search-box" id="search-books" method="post">
<input type="text" id="myInput" name="searchBox" placeholder="seach here" class="form-control">
</form>
</section>
<section class="Movies-section">
<div class="size allMovie actionMovie"><img src="images/movies/bat-man.jpg" alt="Batman">
<div class="Movie-detail">
<h4>Dark Knight</h4>
<p>action</p>
</div>
</div>
<div class="size allMovie actionMovie"><img src="images/movies/blood-shot.jpg" alt="Blood shot">
<div class="Movie-detail">
<h4>Bloodshot</h4>
<p>action</p>
</div>
</div>
<div class="size allMovie dramaMovie"><img src="images/movies/call.jpg" alt="call">
<div class="Movie-detail">
<h4>Call</h4>
<p>drama</p>
</div>
</div>
<div class="size allMovie actionMovie"><img src="images/movies/captain-marvel.png" alt="captain marvel">
<div class="Movie-detail">
<h4>Captain marvel</h4>
<p>action/sci-fi</p>
</div>
</div>
<div class="size allMovie actionMovie"><img src="images/movies/end-game.jpg" alt="avenger end game">
<div class="Movie-detail">
<h4>Avengers end game</h4>
<p>action/sci-fi</p>
</div>
</div>
<div class="size allMovie"><img src="images/movies/hunter-killer.jpg" alt="hunter Killer">
<div class="Movie-detail">
<h4>Hunter killer</h4>
<p>Thriller</p>
</div>
</div>
<div class="size allMovie"><img src="images/movies/insidious.jpg" alt="insidious">
<div class="Movie-detail">
<h4>Insidious</h4>
<p>Horror/Thriller</p>
</div>
</div>
<div class="size allMovie dramaMovie"><img src="images/movies/love-roise.jpg" alt="love roise">
<div class="Movie-detail">
<h4>Love roise</h4>
<p>drama/romance</p>
</div>
</div>
</section>
<footer>
<span>365</span>
<p>Powered by 365 Entertainment Portal 2021. All rights Reserved.</p>
</footer>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" charset="utf-8"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="main.js" charset="utf-8"></script>
</body>
By above logic I m only able to filter genre "all movie" "action movie" but when I try to search after "action" it doesn't work, and also not for "drama movies".

HTML Form - similar input groups as an array of objects

So I have a form with two identical group of inputs that represent education info. There could be more than two as I want to include a button to create a new group so the user can put all his education background like in LinkedIn.
<form id="formCV" action="">
<div id="educationContainer">
<!-- First Group -->
<div class="education">
<div>
<input type="text" name="institutionName">
</div>
<div>
<input type="text" name="courseName">
</div>
<div>
<input type="month" name="startDate">
</div>
<div>
<input type="month" name="endDate">
</div>
</div>
<!-- Second Group -->
<div class="education">
<div>
<input type="text" name="institutionName">
</div>
<div>
<input type="text" name="courseName">
</div>
<div>
<input type="month" name="startDate">
</div>
<div>
<input type="month" name="endDate">
</div>
</div>
</div>
</form>
Now, if I use the FormData API to get the form data like this:
for(let entry of formData.entries()){
console.log(entry);
}
I get the following output:
(2) ["institutionName", "Harvard"]
(2) ["courseName", "Web Development"]
(2) ["startDate", "2000-11"]
(2) ["endDate", "2008-11"]
(2) ["institutionName", "Oxford"]
(2) ["courseName", "Business Management"]
(2) ["startDate", "2009-10"]
(2) ["endDate", "2010-05"]
What I want to achieve is to get the output in an organized way, like this:
education:[
{
institutionName:"Harvard",
courseName:"Web Development",
startDate:"2000-11",
endDate:"2008-11"
},
{
...
}
]
So I'm interested in knowing the best approach to achieve this. Thanks in advance for any help!
It does not make sense to have two equal forms, with one being sufficient.
In addition to the form you should have a list that shows each item added.
It's what I recommend.
Not sure whether this is the best approach, but you can achieve the desired structure like this:
const formCV = document.querySelector('#formCV');
const formData = new FormData(formCV);
function groupEducationData(inputGroupSize = 4) {
const result = [];
let educationObj = null;
let counter = 0;
for (const entry of formData.entries()) {
// Since the counter is divisible by the number of inputs in a group
// only if one form group finishes. And when one form group finishes,
// we need to add the object into the result array
if (counter % inputGroupSize === 0) {
// if this is the first iteration, the educationObj is null and
// we don't want to add it to the result array yet
// we only add the educationObj to the result array if it is
// an object containing the education info
if (educationObj) result.push(educationObj);
// initialize the educationObj at the start
// and after one form finishes
educationObj = {};
}
// add entry[0] as key to the object (e.g. 'institutionName')
// with the value of entry[1] (e.g. 'Harvard')
educationObj[entry[0]] = entry[1];
counter++;
}
return result.concat(educationObj);
}
console.log(groupEducationData());
<form id="formCV" action="">
<div id="educationContainer">
<!-- First Group -->
<div class="education">
<div>
<input type="text" name="institutionName" value="Harvard">
</div>
<div>
<input type="text" name="courseName" value="Web Development">
</div>
<div>
<input type="month" name="startDate" value="2000-11">
</div>
<div>
<input type="month" name="endDate" value="2008-11">
</div>
</div>
<!-- Second Group -->
<div class="education">
<div>
<input type="text" name="institutionName" value="Oxford">
</div>
<div>
<input type="text" name="courseName" value="Business Management">
</div>
<div>
<input type="month" name="startDate" value="2009-10">
</div>
<div>
<input type="month" name="endDate" value="2010-05">
</div>
</div>
</div>
</form>
You can try FormData.getAll() and iterate over each group entry.
const institutionNames = formData.getAll('institutionName');
const courseNames = formData.getAll('courseName');
...
const educations = [];
for (let i = 0; i < institutionNames.length; i++) {
educations.push({
institutionName: institutionNames[i],
courseName: courseNames[i],
...
});
}
This is also a way to populate your desired format data.
$(document).ready(function(){
$(":button").click(function(){
var educations=$("#formCV .education");
var data=[];
educations.each(function(i,education){
var set={}
$(education).find(":input").each(function(i,value){
set[$(value).attr("name")] = $(value).val();
});
data.push(set);
})
console.log("data",data)
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form id="formCV" action="">
<div id="educationContainer">
<!-- First Group -->
<div class="education">
<div>
<input type="text" name="institutionName">
</div>
<div>
<input type="text" name="courseName">
</div>
<div>
<input type="month" name="startDate">
</div>
<div>
<input type="month" name="endDate">
</div>
</div>
<!-- Second Group -->
<div class="education">
<div>
<input type="text" name="institutionName">
</div>
<div>
<input type="text" name="courseName">
</div>
<div>
<input type="month" name="startDate">
</div>
<div>
<input type="month" name="endDate">
</div>
</div>
</div>
<input type="button" value="click me"/>
</form>
</body>
</html>

ng-class to select button based on condition in ng-repeat

I have below code where I am displaying buttons based on array values. I want to select button based on a condition which checks if it matches with another array values. I have added an ng-class to check i in array1 loop matches listApi but couldn't come up with correct logic and get it tow work. Need help please
<label ng-repeat="i inn array1 track by $index">
<label class="btn-primary" ng-click="array1Selection()">
<span ng-class="{'btn-primary': i.name === listApi[0].name}"></span>
{{i.name}}
</label>
</div>
</label>
Your span tag is empty and I think you should put {{i.name}} inside that. also you should not add class 'btn ...' to your label. Hope this code helps you.
var app = angular.module("app", []);
app.controller("MainCtrl", function($scope) {
$scope.array1 = [{
id: 1,
name: "abc"
}, {
id: 1,
name: "xyz"
}];
$scope.listApi = [{
id: 2,
name: "xyz"
}];
$scope.existInList = function(itm) {
let x = $scope.listApi.findIndex(it => {
return it.name == itm.name
});
return x == -1 ? false : true;
}
});
.exists {
color: green
}
.noexists {
color: red
}
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-controller="MainCtrl">
<h2>Add class to existing items and others</h2>
<label ng-repeat="i in array1">
<div data-toggle="buttons">
<label>
<div class="itemcontent">
<input type="checkbox" name="array1Select" />
<span ng-class="{true: 'exists', false: 'noexists'}[existInList(i) === true]">
{{i.name}}
</span>
</div>
</label>
</div>
</label>
<h2>Show only if exists in list</h2>
<label ng-repeat="i in array1">
<div data-toggle="buttons">
<label ng-if="existInList(i)">
<div class="itemcontent">
<input type="checkbox" name="array1Select" />
<span>
{{i.name}}
</span>
</div>
</label>
</div>
</label>
</body>
</html>
I'm not 100% sure JS' find will work inline in Angular but is so...
<label ng-repeat="i inn array1 track by $index">
<div data-toggle="buttons">
<label class="btn btn-w-m btn-primary" ng-click="array1Selection()">
<div class="itemcontent">
<input type="checkbox" name="array1Select" />
<span nng-class="btn btn-w-m btn-primary: listApi.find(a => a.name === i.name)"></span>
{{i.name}}
</div>
</label>
</div>
</label>
A simple modification
var app = angular.module("app", []);
app.controller("MainCtrl", function($scope) {
$scope.array1 = [{ id: 1, name: "abc" }, { id: 1, name: "xyz"
}];
$scope.listApi = [{ id: 2, name: "xyz" }];
$scope.foundInApiList = function(name) {
for(var i = 0; i < $scope.listApi.length; i++)
if($scope.listApi[i].name == name)
return true;
return false;
}
});
.exists {
color: green
}
.noexists {
color: red
}
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-controller="MainCtrl">
<label ng-repeat="i in array1 track by $index">
<div data-toggle="buttons">
<label class="btn btn-w-m btn-primary" ng-click="array1Selection()">
<div class="itemcontent">
<input type="checkbox" name="array1Select" />
<span class="btn btn-w-m btn-primary" ng-class="{true: 'exists', false: 'noexists'}[foundInApiList(i.name)]">{{i.name}}</span>
</div>
</label>
</div>
</label>
</body>
</html>

How to add new option to select if radiobutton is changed using jQuery

I try to add new "items" to a given <select> using jQuery.
If one of the both possibiities (Countries) is checked, the "select-Box" below should change the list <options>.
This is my code:
$("input:radio[name=radio-1]").change(function() {
//alert ($(this).val());
if ($(this).val() == "aut") {
for (i = 18; i < 21; i++) {
$('#selectCosts').append($('<option>', {
value: i,
text: "Option " + i
}));
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="country">
<h2>Land</h2>
<form name="selectPowerCost">
<fieldset>
<div id="selectCountry" class="col col-md-12">
<!-- Österreich -->
<div class="radio pull-left" style="margin-top: -5px; min-width:150px;">
<label for="radio-1">Österreich<span class="country-aut"> </span></label>
<input class="left-20" type="radio" name="radio-1" id="radio-1" value="aut">
</div>
<!-- Deutschland -->
<div class="radio pull-left left-10" style="min-width:150px;">
<label for="radio-2">Deutschland<span class="country-ger"> </span></label>
<input class="left-20" type="radio" name="radio-1" id="radio-2" value="ger">
</div>
</div>
</fieldset>
</form>
</div>
<div id="stromkostenProKW">
<h2>Stromkosten pro KWh</h2>
<div class="pull-left" style="margin-top: -5px">
<form>
<select id="selectCosts" name="selectCosts" class="selectpicker" title="Wählen Sie Ihre Stromkosten pro KWh">
</select>
</form>
</div>
</div>
This code won`t run. Why?
I believe what you want is change option for combobox depending on the selected radio button. What you need to do is to clear the combobox options first before adding new options.
$("input:radio[name=radio-1]").change(function() {
//alert ($(this).val());
var val = $(this).val();
$('#selectCosts').find('option').remove().end();
if (val == "aut") {
for (i = 18; i < 21; i++) {
$('#selectCosts').append($('<option>', {
value: i,
text: "Option " + i
}));
}
} else if(val == "ger") {
for (var i = 1; i < 5; i++) {
$('#selectCosts').append($('<option>', {
value: i,
text: "Option " + i
}));
}
}
});
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js">
</script>
<div id="country">
<h2>Land</h2>
<form id="selectPowerCost" name="selectPowerCost">
<fieldset>
<div class="col col-md-12" id="selectCountry">
<!-- Österreich -->
<div class="radio pull-left" style="margin-top: -5px; min-width:150px;">
<label for="radio-1">Österreich<span class="country-aut"> </span></label> <input class="left-20" id="radio-1" name="radio-1" type="radio" value="aut">
</div><!-- Deutschland -->
<div class="radio pull-left left-10" style="min-width:150px;">
<label for="radio-2">Deutschland<span class="country-ger"> </span></label> <input class="left-20" id="radio-2" name="radio-1" type="radio" value="ger">
</div>
</div>
</fieldset>
</form>
</div>
<div id="stromkostenProKW">
<h2>Stromkosten pro KWh</h2>
<div class="pull-left" style="margin-top: -5px">
<form>
<select class="selectpicker" id="selectCosts" name="selectCosts" title="Wählen Sie Ihre Stromkosten pro KWh">
</select>
</form>
</div>
</div>
</body>
</html>
You only check if the country Austria is checked and not if Germany is checked.
Also i would add $("#selectCosts").empty(); before the loop to empty the items inside the list.
EDIT
You could also replace this part:
$('#selectCosts').append($('<option>', {
value: i,
text: "Option " + i
}));
With this suggestion made by #Taufik Nur Rahmanda:
$('#selectCosts').append('<option value="'+i+'">Option '+i+'</option>');
$("input:radio[name=radio-1]").change(function() {
//alert ($(this).val());
if ($(this).val() == "aut" || $(this).val() == "ger") {
$("#selectCosts").empty();
for (i = 18; i < 21; i++) {
$('#selectCosts').append($('<option>', {
value: i,
text: "Option " + i
}));
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="country">
<h2>Land</h2>
<form name="selectPowerCost">
<fieldset>
<div id="selectCountry" class="col col-md-12">
<!-- Österreich -->
<div class="radio pull-left" style="margin-top: -5px; min-width:150px;">
<label for="radio-1">Österreich<span class="country-aut"> </span></label>
<input class="left-20" type="radio" name="radio-1" id="radio-1" value="aut">
</div>
<!-- Deutschland -->
<div class="radio pull-left left-10" style="min-width:150px;">
<label for="radio-2">Deutschland<span class="country-ger"> </span></label>
<input class="left-20" type="radio" name="radio-1" id="radio-2" value="ger">
</div>
</div>
</fieldset>
</form>
</div>
<div id="stromkostenProKW">
<h2>Stromkosten pro KWh</h2>
<div class="pull-left" style="margin-top: -5px">
<form>
<select id="selectCosts" name="selectCosts" class="selectpicker" title="Wählen Sie Ihre Stromkosten pro KWh">
</select>
</form>
</div>
</div>
Hey Guys/Girls/Developer!
Thx a lot for your support.
I solved my Problem. All suggestions are working fine.
I had included a "bootstrap-select.min.js" which made some conflicts and result in problems. As I excluded this .js-File everything works fine.
Thank you very much!
Here is the code I am using (only JS):
function init() {
$("input:radio[name=radio-1]").change(function() {
var val = $(this).val();
$('#selectCosts').find('option').remove().end();
if (val == "aut") {
for (i = 16; i < 22; i++) {
$('#selectCosts').append($('<option>', {
value: i,
text: "Kosten pro KWh: " + i + " ct"
}));
}
} else if(val == "ger") {
for (var i = 26; i < 33; i++) {
$('#selectCosts').append($('<option>', {
value: i,
text: "Kosten pro KWh: " + i + " ct"
}));
}
}
});
}
document.addEventListener('DOMContentLoaded', init);

How to select all the check boxes in nested ng-repeat

I'm trying to create a list where there are multiple select all buttons to for ng-repeat check boxes.
HTML code
<div class="col-xs-12"ng-repeat="items in testArray">
<div class="col-xs-6">
{{items.brand}}
</div>
<div class="col-xs-6 col-sm-offset-6">
<button ng-click="selectAll()">select All</button>
<div ng-repeat="i in items.form">
<input type="checkbox"/>{{i.formName}}
</div>
</div>
</div>
you can try it.this example you can manipulate it according to your need
https://plnkr.co/edit/qD7CABUF9GLoFCb8vDuO?p=preview
$scope.test=function(event){
if(event.currentTarget.checked==true)
{
var togglestatus=$scope.isAllSelected;
angular.forEach($scope.options,function(object){
object.selected=togglestatus
})
}else{
angular.forEach($scope.options,function(object){
object.selected=false
})
}
}
html:
<body ng-app="test" ng-controller="testctrl">
<label>
<input type="checkbox" ng-model="isAllSelected" ng-click="test($event)">SelectAll</label>
<div ng-repeat="option in options">
<input type="checkbox" ng-model="option.selected">checkbox</div>
</body>
Please check ngChecked directive. You need to add it to your input
<input type="checkbox" ng-checked="i.isChecked" />
and then in selectAll() method set isChecked property on every item to true.
look at code snippet given below , this will give you idea.
var app = angular.module("myApp",[]);
app.controller('demoCtrl',function($scope){
$scope.itemsArray = [{name:"Test 1",forms:[{formName:"xyz 1 "},{formName:"xyz 1 "}]},{name:"Test 2",forms:[{formName:"xyz 2 "},{formName:"xyz 1 "}]},{name:"Test 3 ",forms:[{formName:"xyz 3"},{formName:"xyz 1 "}]}];
$scope.selectAll = function(item){
for(var i =0;i < item.forms.length;i++)
{
item.forms[i].isChecked = true;
}
}
$scope.removeAll = function(item) {
for(var i =0;i < item.forms.length;i++)
{
item.forms[i].isChecked = false;
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="demoCtrl">
<div ng-repeat="item in itemsArray">
<span>{{item.name}}</span>
<button ng-click="selectAll(item)"> select All </button>
<button ng-click="removeAll(item)"> Deselect All </button>
<div ng-repeat="i in item.forms">
<input type="checkbox" ng-model="i.isChecked"/>
</div>
</div>
</div>
</div>
You can simply set a variable to true like this
ng-click="selectAll = true"
and then use the ng-checked directive to set the checkbox to checked when the expression inside is true
ng-checked="selectAll"
HTML
<div class="col-xs-12"ng-repeat="items in testArray">
<div class="col-xs-6">
{{items.brand}}
</div>
<div class="col-xs-6 col-sm-offset-6">
<button ng-click="selectAll = true">select All</button>
<div ng-repeat="i in items.form">
<input type="checkbox" ng-checked="selectAll"/>{{i.formName}}
</div>
</div>
</div>
Created a fiddle, showcasing your need for requirement "select all" - http://jsfiddle.net/deeptechtons/TKVH6/
//html
<div>
<ul ng-controller="checkboxController">
<li>Check All
<input type="checkbox" ng-model="selectedAll" ng-click="checkAll()" />
</li>
<li ng-repeat="item in Items">
<label>{{item.Name}}
<input type="checkbox" ng-model="item.Selected" />
</label>
</li>
</ul>
</div>
//js
angular.module("CheckAllModule", [])
.controller("checkboxController", function checkboxController($scope) {
$scope.Items = [{
Name: "Item one"
}, {
Name: "Item two"
}, {
Name: "Item three"
}];
$scope.checkAll = function () {
if ($scope.selectedAll) {
$scope.selectedAll = true;
} else {
$scope.selectedAll = false;
}
angular.forEach($scope.Items, function (item) {
item.Selected = $scope.selectedAll;
});
};
});

Categories

Resources