Get Selected check box items from a click of a button - javascript

How can I go about getting checked check box item's ID in a repeated list from a click of a button and add items to a variable / Array for later use?
html:
<input id="btnCheck" type="button" value="Next" ng-click="addSelected()" />
<div ng-controller="movieController">
<ul>
<li ng-repeat="movie in Movies">
<input id="chkBox-{{ movie.MovieID }}"
type="checkbox"
ng-checked="selection.indexOf(movie.MovieID) > -1"
ng-click="toggleSelection(movie.MovieID)"
/>
</li>
</ul>
</div>
Script:
$scope.AddSelected = function () {
var selected = $scope.selection
console.log(selected);
}
$scope.selection = [];
$scope.toggleSelection = function toggleSelection(movie) {
var idx = $scope.selection.indexOf(movie);
if (idx > -1) {
$scope.selection.splice(idx, 1);
}
else {
$scope.selection.push(movie);
}
};

You could create a custom filter which would return a selected value id, for that you need pass two parameters to filter 1st parameter will perform check, if it is true then 2nd parameter property array will be return from the filter.
Markup
<body ng-app="app">
<div ng-controller="movieController">
{{(Movies | returnPropertyWhenCheckedTrue: 'checked' :'MovieID')}}
<ul>
<li ng-repeat="m in Movies">
<input id="chkBox-{{ m.MovieID }}" type="checkbox" ng-model="m.checked"/>
</li>
</ul>
</div>
</body>
Filter
app.filter('returnPropertyWhenCheckedTrue', function() {
return function(array, propertyToChecked, property) {
var returnArray = [];
angular.forEach(array, function(value, index) {
if (value[propertyToChecked])
returnArray.push(value[property]);
});
return returnArray;
}
});
Working Plunkr

You can use ng-options for multiple select. More usefull;
<select name="movies" ng-model="selectedMovieIDs"
ng-options="m.MovieID as m.MovieID for m in movies">
</select>
More more info : ngOptions

Related

Get multiple value from dropdown multiple checked checkbox

I creating a dropdown multiple checkbox filter function for my gantt chart, but I'm having trouble getting all selected value and append it into an array. can anyone help me with this, any help is much appreciated
Below is my code :
HTML :
<label class="text-primary" for="type_2">Search Type: </label>
<dl id="type_2" class="dropdown">
<dt>
<a href="#">
<span class="hida">ALL</span>
<p class="multiSel"></p>
</a>
</dt>
<dd>
<div class="search_type_filter">
<ul>
<li><input type="checkbox" value="ALL" selected="Selected" checked="1" />ALL</li>
<li><input type="checkbox" value="Car" />Car</li>
<li><input type="checkbox" value="Bike"/>Bike</li>
<li><input type="checkbox" value="Ball"/>Ball</li>
</ul>
</div>
</dd>
</dl>
Javascript :
$('.search_type_filter input[type="checkbox"]').on('click', function() {
var title = $(this).closest('.search_type_filter').find('input[type="checkbox"]').val(),
title = $(this).val() + ",";
var values = $(this).closest('.search_type_filter').find('input[type="checkbox"]').val(),
values = $(this).val();
search_type_value = {};// put combo value into scope variable
for(var i = 0; i < values.length; i++){
search_type_value[values[i]] = true;// build hash for easy check later
}
console.log(search_type_value);
gantt.render();// and repaint gantt
if ($(this).is(':checked')) {
var html = '<span title="' + title + '">' + title + '</span>';
$('.multiSel').append(html);
$(".hida").hide();
} else {
$('span[title="' + title + '"]').remove();
var ret = $(".hida");
$('.dropdown dt a').append(ret);
}
});
gantt.attachEvent("onBeforeTaskDisplay", function (id, task) {
if(search_type_value['ALL'])
return true;
return !!search_type_value[task.search_type];
});
So the end result what I want is let say I check Car and Ball it will give me an array like this :
{Car: true, Ball: true}
but with this I'm getting by letter and its getting only one value :
{C: true, a: true, r: true}
Here is an example. I added comments that explain whats going on in the code but essentially you just want to create a JSON array based on the checkbox elements on your form.
I also included an alternative to this that uses multi-dimensional arrays but I highly recommend you go down the JSON path instead.
//on button click
$("#click").click(function()
{
//create variable to hold the array
var yourArray = [];
//for each checkbox within the group
$("input[name='group']").each(function()
{
//return if its checked or not
var isChecked = $(this).is(":checked");
//get the value of the checkbox i.e. Bike etc.
var value = $(this).val();
//Create a new object using above variables
var myObject = new Object();
myObject.value = value;
myObject.isChecked = isChecked;
//push the object onto the array
yourArray.push(myObject);
});
//Now you have a dynamic object you can use to select what you need
console.log("Using JSON Array (recommended)");
console.log(yourArray[0].value);
console.log(yourArray[0].isChecked);
console.log(yourArray[1].value);
console.log(yourArray[2].value);
//showing everything in the array
console.log(yourArray);
//if you really need to have the output as Ball:true, Bike:false etc you can break up the array you already have like this:
//Create 2d array
var multiArray = [];
//foreach index in your json array
$.each(yourArray, function(key, value)
{
//create a new array
var newArray = [];
//push the values into it
newArray.push(value.value);
newArray.push(value.isChecked);
//push the array onto the 2d array
multiArray.push(newArray);
});
//output the results
console.log("Using 2D Array");
console.log(multiArray);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="text-primary" for="type_2">Search Type: </label>
<dl id="type_2" class="dropdown">
<dt>
<a href="#">
<span class="hida">ALL</span>
<p class="multiSel"></p>
</a>
</dt>
<dd>
<div class="search_type_filter">
<ul>
<li><input type="checkbox" name="group" value="ALL" selected="Selected" checked="1" />ALL</li>
<li><input type="checkbox" name="group" value="Car" />Car</li>
<li><input type="checkbox" name="group" value="Bike" />Bike</li>
<li><input type="checkbox" name="group" value="Ball" />Ball</li>
</ul>
</div>
</dd>
</dl>
<button type="button" id="click"> check </button>

How to assign key from one variable to value in another, angular

I'm rendering form on a page with help ng-repeat, data for this form comes dynamically from request. In this data I have nested array - categories. Inside of this array defined ids and list of this ids I can see in my form. From another request I get another array where defined names for ids. How can I assign key value from one variable to key value from another variable that display on the page list of names instead of list of ids
This is plunker with my problem. I appreciate any help, thanks in advance.
html of my form
<form style="padding: 15px" ng-submit="submitForm(rowData)">
<div class="form-group row">
<div ng-repeat="(key, value) in rowData">
<div ng-if="key | id">
<label class="col-sm-6">{{key | makeUppercase}}</label>
<div class=" col-sm-6">
<input class="form-control rowValue"
id="rowData[key]"
ng-if="!isObject(value)"
type="text"
ng-model="rowData[key]"
/>
<span
class="form-control rowValue"
id="categories"
ng-if="isObject(value) && key == 'categories'"
ng-model="rowData.categories">
{{rowData.categories}}
</span>
</div>
</div>
</div>
</div>
<div class="pull-right">
<button type="submit" class="btn btn-default"
ng-if="rowData">Save</button>
<button type="button" class="btn btn-default" ng-if="rowData"
ng-click="cancelForm()">Cancel</button>
</div>
</form>
My implementation is very naive but it displays what you want.
I add this function to your controller
$scope.getCategoryIns = function(ids){
var categoriesName = [];
for (var j = 0; j < ids.length; j ++){
id = ids[j];
for(var i= 0; i < $scope.categories.length;i++)
{
if ( $scope.categories[i].id == id){
categoriesName.push($scope.categories[i].name);
}
}
}
var str = categoriesName.join(', ');
return str;
}
and in HTML use this function as following
<span class="form-control rowValue" id="categories" ng-if="isObject(value) && key == 'categories'" ng-model="rowData.categories">
{{getCategoryIns(rowData.categories)}}</span>
plnkr here
You could create a new method in your controller that maps the numbers in $scope.rowData.categories to $scope.categories.id and returns values of the corresponding category names:
$scope.getCategoryName = function (categoriesArr) {
return categoriesArr.map(function(curr) {
return $scope.categories.filter(function(el){
return el.id === curr; //filter out the appropriate category by id
})[0].name; //select the item and grab its name property
})
}
and update your HTML to use the new method:
<span>
class="form-control rowValue"
id="categories"
ng-if="isObject(value) && key == 'categories'"
ng-model="rowData.categories">
{{getCategoryName(rowData.categories)}}
</span>

angular ng-disable checkbox not update with dynamic source

I have several checkboxes dynamicaly generated from array source:
/*js*/
$scope.arrondissements = JSON.parse('
[{"name":"4e","checked":false,"disable":true},
{"name":"5e","checked":false,"disable":false},
{"name":"11e","checked":false,"disable":false},
{"name":"12e","checked":false,"disable":false},
{"name":"13e","checked":false,"disable":false},
{"name":"14e","checked":false,"disable":false},
{"name":"15e","checked":false,"disable":false},
{"name":"16e","checked":false,"disable":false},
{"name":"17e","checked":false,"disable":false},
{"name":"18e","checked":false,"disable":false},
{"name":"19e","checked":false,"disable":false},
{"name":"20e","checked":false,"disable":false}]');
<!-- HTML -->
<div ng-repeat="item in arrondissements" class="checkbox-inline ">
<label>
<input type="checkbox" ng-disabled="{{item.disable == true}}"
value="{{item.checked}}" ng-model="item.checked" >
<span>{{item.name}}</span>
</label>
</div>
Checkboxes are generated correctly but When source gets updated , checkbox doesn't update
/*js*/
$scope.disableCb = function () {
$scope.arrondissements[5].disable = true;
$scope.arrondissements[6].disable = true;
$scope.arrondissements[7].disable = true;
}
<!-- HTML -->
<button ng-click="disableCb()">disable</button>
Could you tell me why and how to fix it?
I made a Plunker : http://plnkr.co/edit/jD1l3NgJuduTOoskpeVM
You should define your $scope.disableCb function inside your controller function.
function controller( $scope) {
var vm = $scope;
$scope.title = 'controller';
$scope.arrondissements = JSON.parse('[{"name":"4e","checked":true,"disable":true},{"name":"5e","checked":false,"disable":false},{"name":"11e","checked":false,"disable":false},{"name":"12e","checked":false,"disable":false},{"name":"13e","checked":false,"disable":false},{"name":"14e","checked":false,"disable":false},{"name":"15e","checked":false,"disable":false},{"name":"16e","checked":false,"disable":false},{"name":"17e","checked":false,"disable":false},{"name":"18e","checked":false,"disable":false},{"name":"19e","checked":false,"disable":false},{"name":"20e","checked":false,"disable":false}]');
$scope.disableCb = function () {
$scope.arrondissements[5].disable = true;
$scope.arrondissements[6].disable = true;
$scope.arrondissements[7].disable = true;
}
}
I've also fixed how you used your directives. I've removed the value attribute on the checkboxes since they're redundant with ng-model.
I've fixed your usage of ng-disabled as well
<div ng-repeat="item in arrondissements" class="checkbox-inline ">
<label>
<input type="checkbox" ng-disabled="item.disable"
ng-model="item.checked" >
<span>{{item.name}}</span>
</label>
</div>
<button ng-click="disableCb()">disable</button>
see my fork on your plunker: http://plnkr.co/edit/v1fwlf7QH0189WAhv6qM?p=preview

Adding event on ng-repeat element

I am very new to angular :). I would like to add a simple event one form element with a particular value, built by ng-repeat. This is how the HTML looks:
<div class="labels">
<div class="checkbox-element" ng-repeat="suggestName in $ctrl.suggests" ng-click="$ctrl.toggleSelection(suggestName, 'suggestsSelection', this)">
<label>
<input type="checkbox" name="suggestsSelection[]"
class="hidden"
value="{{suggestName}}"
><span></span>{{suggestName}}
</label>
</div>
<div class="optionary hidden">
<br>
<div class="question__text">Any other?</div>
<label><input type="text"
ng-model="$ctrl.survey.suggest_other"
name="suggests_other1"></label><br>
</div>
</div>
And the controller code:
vm.survey = {};
vm.suggests = ['quality', 'price', 'habbit', 'other'];
// selected
vm.survey.suggestsSelection = [];
// toggle selection for a given names
vm.toggleSelection = function toggleSelection(value, array, scope) {
var idx = vm.survey[array].indexOf(value);
// is currently selected
if (idx > -1) {
vm.survey[array].splice(idx, 1);
}
// is newly selected
else {
vm.survey[array].push(value);
}
};
What I need is to create an event that would toggle the class "hidden" from the div with class "optionary" after clicking on the last created checkbox ("other" in this case). Clicking on other checkboxes shouldn't affect the "optionary" div.
I tried with some configurations like:
if(scope.$last){
$(scope).closest('.optionary').toggleClass('hidden');
}
or similar. I don;t know what should be the way to approach the topic.
You need to use ng-show and a control variable. Take a look.
jsFiddle here: https://jsfiddle.net/U3pVM/24834/
<div ng-app class="labels" ng-controller="MyCtrl">
<div class="checkbox-element" ng-repeat="suggestName in suggests" ng-click="toggleSelection(suggestName, suggestsSelection, this)">
<label>
<input type="checkbox" ng-model="cbSuggest[$index]" name="suggestsSelection[]" class="hidden" value="{{suggestName}}">
<span>{{suggestName}}</span>
</label>
</div>
<div class="optionary hidden" ng-show="showOther">
<br>
<div class="question__text">Any other?</div>
<label><input type="text" ng-model="survey.suggest_other" name="suggests_other1"></label><br>
</div>
</div>
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.survey = {};
$scope.suggests = ['quality', 'price', 'habbit', 'other'];
$scope.cbSuggest = [];
$scope.showOther = true;
// selected
$scope.survey.suggestsSelection = [];
// toggle selection for a given names
$scope.toggleSelection = function(value, array, scope) {
var showOther = true;
angular.forEach($scope.cbSuggest, function(k,v){
if(k) {
showOther = false;
}
});
$scope.showOther = showOther;
};
}
As you can see ng-repeat has special properties: https://docs.angularjs.org/api/ng/directive/ngRepeat
The one you're interested in is $last. You could add ng-change to your checkboxes, call a function with the paramter $last, and that function would set a scope variable. The hidden class could rely on that.
Something like this:
<input type="checkbox" name="suggestsSelection[]"
class="hidden"
ng-change="showHidden($last)"
value="{{suggestName}}">
And in your controller:
$scope.hidden = true;
$scope.showHidden = function(isLast) {
if (isLast) $scope.hidden = false;
else $scope.hidden = true;
}
And then you add ng-class to your div:
<div class="optionary" ng-class="{'hidden': hidden}">...</div>

jQuery - Getting values of text input and checkboxes into one string (or array)

I have three types of items I'm trying to get into a comma-separated string (or array), which I want to display and use to form a URL later.
How can I get these three types of data into the same string or array?
An existing POST string
Free input from a text field with an Add button
The values of a series of checkbokes
Currently, with the code I'm using, adding the form input values overrides the string, and I can't figure out how to remove a checkbox value from the string when its box is unchecked.
Here's the fiddle.
I'm using this HTML:
<div class="srs-display">existingPostString</div>
<ul id="srs" class="srs">
<!-- START TEXT INPUT FIELD -->
<li class="sr">
<div class="masonry-well">
<input id="sr-custom" type="text" placeholder="Add your own">
<a class="add-sr-custom">Add</a>
</div>
</li>
<!-- END TEXT INPUT FIELD -->
<!-- START CHECKBOXES -->
<li class="sr">
<div class="masonry-well">
<input id="srPredefined1" type="checkbox" name="srPredefined1" value="srPredefined1">
<label for="srPredefined1" class="ts-helper">srPredefined1</label>
</div>
</li>
<li class="sr masonry-item">
<div class="masonry-well">
<input id="srPredefined2" type="checkbox" name="srPredefined2" value="srPredefined2">
<label for="srPredefined2" class="ts-helper">srPredefined2</label>
</div>
</li>
<li class="sr masonry-item">
<div class="masonry-well">
<input id="srPredefined3" type="checkbox" name="srPredefined3" value="srPredefined3">
<label for="srPredefined3" class="ts-helper">srPredefined3</label>
</div>
</li>
<!-- END CHECKBOXES -->
</ul>
And here's the JS I tried so far:
$('input[type="checkbox"]').bind('change', function() {
var srs = 'existingPostString';
$('input[type="checkbox"]').each(function(index, value) {
if (this.checked) {
/*add*/ /*get label text associated with checkbox*/
srs += ($(this).val() + ', ');
}
});
if (srs.length > 0) {
srs = srs.substring(0,srs.length-2);
} else {
srs = 'No checks';
}
$('.srs-display').html(srs);
});
$(".add-sr-custom").on('click', function() {
var srs = 'existingPostString';
srs += ',' + $('#sr-custom').val();
$('.srs-display').text(srs);
})
I would push your string elements to an array, and then call array.join(',') on it. Like this:
var srs = [];
//each checkbox
srs.push($(this).val());
//later
var new_string = srs.join(',');
Hi man check this solution:https://jsfiddle.net/leojavier/onwkaLet/6/
var srs = [];
$('input[type="checkbox"]').bind('change', function() {
srs=[]
$('input[type="checkbox"]').each(function(index, value) {
if (this.checked) {
srs.push($(this).val());
}
});
$('.srs-display').html(srs);
});
$(".add-sr-custom").on('click', function() {
$('#sr-custom').val(srs);
})

Categories