Angular checkbox to filter data - javascript

I am showing FreeEvents using checkbox. I am passing the value to the filter as filter:filterFreeEvent . This is working fine.
But I want to avoid passing value in the filter rather I want to use a change event of a checkbox to filter.
Something like
<input type="checkbox" ng-model="showFreeEvent" ng-change($event)">
This is my JsFiddle example.
Has anyone done something like this?. Any help or suggestion would be appreciated.
Thanks in advance

You can also change a variable in the change-event only like this :
<input ng-model="changeValue" ng-change="showFreeEvent = showFreeEvent== false ? true : false" value="" type="checkbox" />
If the showFreeEvent is false, ng-change will change it to true and vice-versa.

You can use ng-change to handle the checkbox change event. Then you can use Array.prototype.filter to filter your events. Filtered events should be stored in a separate variable. Here is an example of how to do this:
<input ng-model="showFreeEvents" type="checkbox" ng-change="onShowFreeEventsChanged()" />
<div ng-controller="myCtrl">
<div ng-repeat="event in filteredEvents">
<span>{{event.eventName}}</span></br>
<span>{{event.eventStartDateTime}}</span></br>
<span>{{event.itemCreatedDateTime}}</span></br>
</br></br>
</div>
</div>
Then in your controller:
$scope.showFreeEvents = false;
$scope.events = [ /* here you should store unfiltered events */ ];
$scope.filteredEvents = filterEvents($scope.events);
// whenever showFreeEvents checkbox value changes, re-filter the events
$scope.onShowFreeEventsChanged = function() {
$scope.filteredEvents = filterEvents($scope.events);
};
function filterEvents(events) {
return events.filter(function(event) {
// Here you should write your filtering logic.
// I'd recommend to remove such comparisons, as these are prone to errors.
// \
return !$scope.showFreeEvents || event.eventName === 'Event 9';
});
}

Related

What is the opposite of :checked [duplicate]

I have a list of checkboxes:
<input type="checkbox" name="answer" id="id_1' value="1" />
<input type="checkbox" name="answer" id="id_2' value="2" />
...
<input type="checkbox" name="answer" id="id_n' value="n" />
I can collect all the values of checked checkboxes; my question is how can get all the values of unchecked checkboxes? I tried:
$("input:unchecked").val();
to get an unchecked checkbox's value, but I got:
Syntax error, unrecognized expression: unchecked.
Can anybody shed a light on this issue?
Thank you!
As the error message states, jQuery does not include a :unchecked selector.
Instead, you need to invert the :checked selector:
$("input:checkbox:not(:checked)")
$("input:checkbox:not(:checked)") Will get you the unchecked boxes.
Also it can be achieved with pure js in such a way:
var matches = document.querySelectorAll('input[type="checkbox"]:not(:checked)');
You can do so by extending jQuerys functionality. This will shorten the amount of text you have to write for the selector.
$.extend($.expr[':'], {
unchecked: function (obj) {
return ((obj.type == 'checkbox' || obj.type == 'radio') && !$(obj).is(':checked'));
}
}
);
You can then use $("input:unchecked") to get all checkboxes and radio buttons that are checked.
$("input[type='checkbox']:not(:checked):not('\#chkAll\')").map(function () {
var a = "";
if (this.name != "chkAll") {
a = this.name + "|off";
}
return a;
}).get().join();
This will retrieve all unchecked checkboxes and exclude the "chkAll" checkbox that I use to check|uncheck all checkboxes. Since I want to know what value I'm passing to the database I set these to off, since the checkboxes give me a value of on.
//looking for unchecked checkboxes, but don’t include the checkbox all that checks or unchecks all checkboxes
//.map - Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.
//.get - Retrieve the DOM elements matched by the jQuery object.
//.join - (javascript) joins the elements of an array into a string, and returns the string.The elements will be separated by a specified separator. The default separator is comma (,).
You can use like this :
$(":checkbox:not(:checked)")
To select by class, you can do this:
$("input.className:checkbox:not(:checked)")
$(".clscss-row").each(function () {
if ($(this).find(".po-checkbox").not(":checked")) {
// enter your code here
} });

Clear input ng-model when ng-show is false AngularJS

Hi I have a small problem.
I have an input bar which sometimes need to be shown in a form and sometimes not.
I am afraid that if someone put data and then hide it and press send, the data will be sent. So I want to reset the input each time it is hidden.
ng-change isn't a good idea because it doesn't let my write anything.
<div class="form-group" ng-show="isItOne=='1' || isItTwo=='2'">
<label class="col-md-1">someName</label>
<div class="col-md-4">
<input class="form-control" type="text" name="someOtherName" ng-model="nameModel" ng-change="clearWhenChanged()">
</div>
</div>
and this is the function
$scope.clearWhenChanged = function() {
$scope.nameModel = "";
};
take out the show condition and use it to control visibility and model value.
$scope.showHideField = function(){
if(isItOne=='1' || isItTwo=='2'){
return true;
}
$scope.nameModel= "";
}
call it in your div:
<div class="form-group" ng-show="showHideField()">
this also provides the flexibility to pass a flag based on which you can decide whether to clear the field's value or not .. :)
You could call a function instead where you set the isItOne variable. In that function you could set the variable to 1 or 2 and clear the model value.
HTML
<div class="form-group" ng-show="show()">
<label class="col-md-1">someName</label>
<div class="col-md-4">
<input class="form-control" type="text" name="someOtherName" ng-model="nameModel" ng-change="clearWhenChanged()">
</div>
</div>
Controller
$scope.show = function() {
if ($scope.isItOne == '1' || $scope.isItOne == '2');
return true;
$scope.nameModel = '';
}
Having said all that it might be a better option to just simply unset the model's value on submit in cases when you don't want it to be sent.
use the tag attribute ng-if="your condition", This will render the tag only when the condition is true. Otherwise it will remove the whole input from DOM.

Angular checkbox input ng-click never called

In my Angular app, I have a form with checkbox inputs:
<div ng-repeat="partner in type.partners">
<label class="checkbox-inline">
<input type="checkbox" value="partner"
ng-checked="report.participatingPartners[$parent.$index].indexOf(partner) !== -1"
ng-click="toggleSelection($parent.$index, $index);">
<p><span></span>{{partner.name}}<p>
</label>
</div>
And in my controller, just to test this setup:
var vm = this;
vm.toggleSelection = toggleSelection;
...
function toggleSelection(typeId, partnerId) {
console.log("toggleSelection called");
console.log(typeId, partnerId);
}
This function never gets called when I click the checkbox or its label. Why is that?
I know it's not the controllerAs syntax because other functions are working fine.
The attribute you probably want to use is ng-change. The angular input directive does not have ng-clicked or ng-checked.
See docs.
By putting the function that you are trying to reference in the ng-click onto $scope rather than onto this the click event should bind as desired.
On the controller...
$scope.toggleSelection = toggleSelection;
function toggleSelection(typeId, partnerId) {
...
}
On your html...
<input type="checkbox" value="partner"
ng-click="toggleSelection($parent.$index, $index);">
Here is a simple Fiddle of it working.
You have written below code:
ng-checked="vm.toggleSelection($parent.$index, $index);"
But it should be:
ng-checked="toggleSelection($parent.$index, $index);"
Just remove "vm"

how to know if a radio button is checked or not in controller in angularjs

I am using radio buttons and I want to know if they are checked or not in the controller. Is there any other way to find that out in angular except ( document.getElementById( "radio_button" ).checked ) ?
You can trigger the function on click like this :
In HTML :
<div ng-click='newValue(value)'>
<input type="radio" ng-model="value" value="firstValue">
<input type="radio" ng-model="value" value="secondValue" > </div>
You can also observe the model change by using ng-change as follows :
In Javascript :
$scope.newValue = function (value) {
alert(value);
}
You can even watch the value by using $watch like this :
$scope.$watch('value', function(value) {
alert(value);
});
However, using ng-change is better and efficient than $watch and is easier to test.
There is no need of $watch
You can do it in more simpler way.
<body ng-controller="testCtrl">
<label>Check me to check both:
<input type="checkbox" ng-model="master" ng-checked="checkTest(master)"></label><br/>
</body>
JS :
$scope.checkTest = function(boolChecked){
console.log(boolChecked)
}
Here is Plunker
You can do this in a few different ways:
with Radio Buttons
In your HTML
<input type="radio" ng-value="isButtonChecked">
In your controller
$scope.isButtonChecked = true;
with another element tag
In your HTML
<div ng-click="isButtonChecked = !isButtonChecked"></div>
In your controller
$scope.isButtonChecked = true;

Change/Get check state of CheckBox

I just want to get/change value of CheckBox with JavaScript. Not that I cannot use jQuery for this. I've tried something like this but it won't work.
JavaScript function
function checkAddress()
{
if (checkAddress.checked == true)
{
alert("a");
}
}
HTML
<input type="checkbox" name="checkAddress" onchange="checkAddress()" />
Using onclick instead will work. In theory it may not catch changes made via the keyboard but all browsers do seem to fire the event anyway when checking via keyboard.
You also need to pass the checkbox into the function:
function checkAddress(checkbox)
{
if (checkbox.checked)
{
alert("a");
}
}
HTML
<input type="checkbox" name="checkAddress" onclick="checkAddress(this)" />
You need to retrieve the checkbox before using it.
Give the checkbox an id attribute to retrieve it with document.getElementById(..) and then check its current state.
For example:
function checkAddress()
{
var chkBox = document.getElementById('checkAddress');
if (chkBox.checked)
{
// ..
}
}
And your HTML would then look like this:
<input type="checkbox" id="checkAddress" name="checkAddress" onclick="checkAddress()"/>
(Also changed the onchange to onclick. Doesn't work quite well in IE :).
I know this is a very late reply, but this code is a tad more flexible and should help latecomers like myself.
function copycheck(from,to) {
//retrives variables "from" (original checkbox/element) and "to" (target checkbox) you declare when you call the function on the HTML.
if(document.getElementById(from).checked==true)
//checks status of "from" element. change to whatever validation you prefer.
{
document.getElementById(to).checked=true;
//if validation returns true, checks target checkbox
}
else
{
document.getElementById(to).checked=false;
//if validation returns true, unchecks target checkbox
}
}
HTML being something like
<input type="radio" name="bob" onclick="copycheck('from','to');" />
where "from" and "to" are the respective ids of the elements "from" wich you wish to copy "to".
As is, it would work between checkboxes but you can enter any ID you wish and any condition you desire as long as "to" (being the checkbox to be manipulated) is correctly defined when sending the variables from the html event call.
Notice, as SpYk3HH said, target you want to use is an array by default. Using the "display element information" tool from the web developer toolbar will help you find the full id of the respective checkboxes.
Hope this helps.
You need this:
window.onload = function(){
var elCheckBox=document.getElementById("cbxTodos");
elCheckBox.onchange =function (){
alert("como ves");
}
};
Needs to be:
if (document.forms[0].elements["checkAddress"].checked == true)
Assuming you have one form, otherwise use the form name.
As a side note, don't call the element and the function in the same name it can cause weird conflicts.
<input type="checkbox" name="checkAddress" onclick="if(this.checked){ alert('a'); }" />
I know this is late info, but in jQuery, using .checked is possible and easy!
If your element is something like:
<td>
<input type="radio" name="bob" />
</td>
You can easily get/set checked state as such:
$("td").each(function()
{
$(this).click(function()
{
var thisInput = $(this).find("input[type=radio]");
var checked = thisInput.is(":checked");
thisInput[0].checked = (checked) ? false : true;
}
});
The secret is using the "[0]" array index identifier which is the ELEMENT of your jquery object!
ENJOY!
This is an example of how I use this kind of thing:
HTML :
<input type="checkbox" id="ThisIsTheId" value="X" onchange="ThisIsTheFunction(this.id,this.checked)">
JAVASCRIPT :
function ThisIsTheFunction(temp,temp2) {
if(temp2 == true) {
document.getElementById(temp).style.visibility = "visible";
} else {
document.getElementById(temp).style.visibility = "hidden";
}
}
var val = $("#checkboxId").is(":checked");
Here is a quick implementation with samples:
Checkbox to check all items:
<input id="btnSelectAll" type="checkbox">
Single item (for table row):
<input class="single-item" name="item[]" type="checkbox">
Js code for jQuery:
$(document).on('click', '#btnSelectAll', function(state) {
if ($('#btnSelectAll').is(':checked')) {
$('.single-item').prop('checked', true);
$('.batch-erase').addClass('d-block');
} else {
$('.single-item').prop('checked', false);
$('.batch-erase').removeClass('d-block');
}
});
Batch delete item:
<div class="batch-erase d-none">
<a href="/path/to/delete" class="btn btn-danger btn-sm">
<i class="fe-trash"></i> Delete All
</a>
</div>
This will be useful
$("input[type=checkbox]").change((e)=>{
console.log(e.target.checked);
});

Categories

Resources