How to make click button from js script in angularjs? - javascript

I want to click checkbox from one of my function of script but i do not know how to do it in angularjs?
I have tried following way but it is not working :
JS
var a = document.getElementById("selectAllElem");
$scope.selectAll = a["onclick"];
if (typeof($scope.selectAll) == "function") {
alert("call click");
$scope.selectAll(a);
}
HTML
<input type="checkbox" ng-click="selectAll($event)" id="selectAllElem" />
Can anyone show me how to make checkbox click from js script in angularjs?
UPDATE
I can not use just single flag variable because above checkbox is placed at header of table and on click of it i need to make all selected check box as deselect and deselected check box as selected.
I need to call button click to achieve target.
how to make checkbox click from js script in angularjs?

you can use this instead of above code :
<input type="checkbox" ng-click="selectAll()" id="selectAllElem" ng-model="allSelected" />
in controller create function selectAll():
$scope.selectAll=function(){
$scope.allSelected=true;
}

UPDATED
You can bind scope variables to all checkboxes and change them in the selectAll() method handling the click.
Also, you could then bind a method to the selectAllElem checkbox, checking if all other checkboxes are selected.
I renamed selectAll() to toggleAll() to show how to select/deselect in one method.
e.g.:
<input ... ng-click="toggleAll()" ng-model="allSelected()" />
and
$scope.allSelected = function(){
return $scope.option1 && $scope.option2;
}
$scope.toggleAll = function(){
var value = !$scope.allSelected();
$scope.option1 = value;
$scope.option2 = value;
}
In case of the checkboxes being generated from an array, you can have scope.options and iterate over it in both methods.
OLD
You could bind the input to a scope variable, e.g.:
<input type="checkbox" ng-click="selectAll($event)" id="selectAllElem" ng-model="allSelected" />
And then set that variable from within the function
$scope.allSelected = true;

Related

How to grab ID of element which ID has been dynamically given?

I’m trying to make a simple show when checkbox is checked kind of section but am unable to get a hold of the element because the IDs of the element are assigned dynamically by PHP.
The element will be inside a foreach loop so there will be multiple instances of it with dynamically given IDs.
example:
//Laravel blade template
<element id="attrb{{ $elem->id }}> "></element>
//Javascript
if ($("#attrb*ID").is(":checked")) {
$("#attrbs-container").show();
} else {
$("#attrbs-container").hide();
}
With Jquery
$('input[id^="attrb"]').change(function(e){
if($(this).is(':checked')) console.log($(this).prop('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="attrb1" value="1" />
Run, and check the box. You can replace console.log with your .show or whatever.
The selector input[id^="attrb"] means an input with an id that ^= starts with attrb. You could also use input[type="checkbox"] if these are the only checkboxes you have, but it's less specific.
Change vs Click
change fires when the data (state) of the element changes. click will trigger anytime you click. In this case it probably doesn't matter too much which you use. A better example of change vs click is using radio buttons, and clicking an already checked radio. Checkboxes un-click when checked, radio buttons not so much. I'm just in a habit of using change over click for state changes.
$('input[id^="attrb"]').click(function(e){
if($(this).is(':checked')) console.log($(this).prop('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" id="attrb1" value="1" />
Run and click the radio 2x. It fires 2 times.
$('input[id^="attrb"]').change(function(e){
if($(this).is(':checked')) console.log($(this).prop('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" id="attrb1" value="1" />
Do the same thing here, but with change. That's the difference.
DYNAMIC vs Dynamic
What I mean here is DYNAMIC is something that changes at run time on the client, Dynamic is static HTML where the ID changes on the server side only. For DYNAMIC you want to use on like this
$(someparent).on('change', 'input[id^="attrb"]', function(e){ ... });
Where someparent is a static element that doesn't change at runtime. This will use event delegation and "bubbling" to find the content that was changed on the client side.
I don't think you meant DYNAMIC but I included it just in case.
Cheers!
you could create a function with a callback if you're assigning the id with javascript (after an ajax request)
function addID(add, callback)
Then use the funciton:
addId(function(){
//dynamically add ID
}, function(){
// callback function
if ($(“#attrb*ID”).is(":checked")) {
$(“#attrbs-container").show();
} else {
$(“#attrbs-container").hide();
}
})

Detect if checkbox is checked or unchecked in Angular.js ng-change event

I want to detect if a checkbox has been checked or unchecked when a click is happening on the checkbox.
This is what I have:
<input type="checkbox" ng-model="answers[item.questID]" ng-change="stateChanged()" />
And then in the controller I have:
$scope.stateChanged = function () {
alert('test');
}
I'm able to fire the alert when I do check/uncheck but how can I detect the state of the checkbox? I did research a bit to find a similar issue but I wasn't able to get what I need.
You could just use the bound ng-model (answers[item.questID]) value itself in your ng-change method to detect if it has been checked or not.
Example:-
<input type="checkbox" ng-model="answers[item.questID]"
ng-change="stateChanged(item.questID)" /> <!-- Pass the specific id -->
and
$scope.stateChanged = function (qId) {
if($scope.answers[qId]){ //If it is checked
alert('test');
}
}
The state of the checkbox will be reflected on whatever model you have it bound to, in this case, $scope.answers[item.questID]

Get widgetVar with JavaScript or check/uncheck all other PrimeFaces checkboxes

I have several PrimeFaces checkboxes on a page. If you click the master checkbox, all other checkboxes should be checked/unchecked. With plain HTML checkboxes this would be an easy issue. But because PrimeFaces does not show the checkbox itself, but an image, the following JavaScript code does not work:
<script type="text/javascript">
$(document).ready(function() {
var masterCheckbox = $(".ui-chkbox.master :checkbox");
var slaveCheckboxes = $(".ui-chkbox:not(.master) :checkbox");
updateMaster();
masterCheckbox.change(updateSlaves);
slaveCheckboxes.change(updateMaster);
function updateMaster() {
var allSlavesChecked = true;
slaveCheckboxes.each(function() {
if (!$(this).is(':checked')) {
allSlavesChecked = false;
}
});
masterCheckbox.attr("checked", allSlavesChecked);
}
function updateSlaves() {
var masterChecked = masterCheckbox.is(":checked");
slaveCheckboxes.each(function() {
$(this).attr("checked", masterChecked);
});
}
});
</script>
I know that I could use the PrimeFaces widgetVar to toggle the checkboxes, but I do not know how to get the PrimeFaces widget objects with JavaScript. I think RichFaces adds the component property to the DOM element, but PrimeFaces does not. Does somebody know a solution for this problem?
You were correct -- if you create your component like this:
<p:selectBooleanCheckbox value="val" widgetVar="myCheckbox"/>
You can access the checkbox simply by refering to its widgetVar, in this case calling the PrimeFaces client-side API to mark it as checked:
<script>
myCheckbox.check();
</script>
You could then tie the onchange event of your master checkbox to a javascript method that checked or unchecked the state of all the "slave" checkboxes depending on the state of the master checkbox (would suggest you store the state in a hidden field).
Note, it may make your life easier to instead handle the "change" ajax event and implement the check/uncheck logic on the server side. Just make sure that you provide all the ids of all the slave checkboxes in the update attribute of the p:ajax component:
<p:selectBooleanCheckbox id="masterChkBox" ...>
<p:ajax event="change" listener="#{yourBean.handleMasterChange}" update="...all slavecheckbox ids..."/>
</p:selectBooleanCheckbox>

How to disable enable a checkbox based on another checkbox?

Following code is generated by a for loop.
<form action="saveresponse.php" method="POST" name="mainForm">
<input class="cbox_yes" type="checkbox" name="yes[]" value="01.jpg"
onclick="spenable()" /> OK
<input class="cbox_sp" type="checkbox" name="sp[]" value="01.jpg" disabled />Special<br />
<input class="cbox_yes" type="checkbox" name="yes[]" value="02.jpg"
onclick="spenable()" /> OK
<input class="cbox_sp" type="checkbox" name="sp[]" value="02.jpg" disabled />Special<br />
etc etc upto n times...
Now, what I want is that on page load, all the sp[] checkboxes should be disabled and enabled only if their corrosponding yes[] checkbox is checked by user.
Javascript code I am using: (Just to check if JS is capturing the states of yes[] checkbox?
function spenable(){
var yes = document.mainForm.yes[].value;
if (yes == true)
//alert("true");
document.mainForm.yes[].value = checked;
else
//alert("false");
document.mainForm.yes[].value = checked;
};
};
But I am not getting any alert (Neither Yes, Nor No).
So, is yes[] (Square brackets) in second line is incorrect? Or my if/else condition is wrong in JS?
P.S. All the questions here at SO or on Google deal with only one case/pair.
P.S. If required, I can change yes[] to yes1, yes2, yes3 etc and corresponding sp1, sp2, sp3 where 1,2,3 is $i of For loop, but then how will I capture/refer to it in JS?
_UPDATE:_
The flow/conditions are(Clarification):
Initially Special checkbox will be disabled and OK checkbox will be unchecked.
Then if user checks Ok, Special gets enabled.
If user want, he can tick Special.
If, later, user changes mind and untick the OK, Special should be unticked as well as disabled again.
I used jQuery here for the sake of simplicity.
$("input[name='yes[]']").change(function() { //When checkbox changes
var checked = $(this).attr("checked");
$(this).next().attr("disabled", !checked); //The next checkbox will enable
});​ // or disable based on the
// checkbox before it
Demo: http://jsfiddle.net/DerekL/Zdf9d/
Pure JavaScript: http://jsfiddle.net/DerekL/Zdf9d/1/
Update
It will uncheck the first checkboxes when the Special checkbox is checked.
Pure JavaScript: http://jsfiddle.net/DerekL/Zdf9d/2/
More Updates
Here's the demo:
Pure JavaScript: http://jsfiddle.net/DerekL/Zdf9d/3/
jQuery: http://jsfiddle.net/DerekL/Zdf9d/4/
Little note: document.querySelectorAll works on all modern browsers and IE8+ including IE8. It is always better to use jQuery if you want to support IE6.
You can't use yes[] as an identifier in the Javascript, so you have to access the field using the name as a string:
document.mainForm["yes[]"]
This will not return a single element, it will return an array of elements. Use an index to access a specific element:
document.mainForm["yes[]"][0]
The value of the checkbox will always be the value property, regardless of whether the checkbox is selected or not. Use the checked property to find out if it's selected:
function spenable() {
var yes = document.mainForm["yes[]"][0].checked;
if (yes) {
alert("true");
} else {
alert("false");
};
}
To access the specific checkbox that was clicked, send the index of the checkbox in the event call:
<input class="cbox_yes" type="checkbox" name="yes[]" value="01.jpg" onclick="spenable(0);" /> OK
Use the index in the function:
function spenable(idx) {
var yes = document.mainForm["yes[]"][idx].checked;
var sp = document.mainForm["sp[]"][idx];
sp.disabled = !yes;
}
If you are open to using jQuery:
$('input[type="checkbox"]').click(function(){
var obj = $(this);
obj.next('.cbox_sp').attr({'disabled':(obj.is(':checked') ? false : 'disabled')});
});
This solution will assign an onclick event handler to all checkboxes and then check to see if the corresponding "special" checkbox should be disabled or not. It also sets the default checked state to true.
Working Example: http://jsfiddle.net/6YTqC/

Check if a checkbox is checked in JS

I am new to js and jquery. Currently, I have a form at form.php which contains a checkbox. When the user clicks submit, the form variables are sent to a form.js file where each value is checked to be null or not.
The form.js file works perfectly, however, for the checkbox nothing seems to happen. I have a feeling this is due to the way I have declared the variable.
The following is the code for the js file:
var email = $('#email').val();
var website = $('#website').val();
var CHECKBOX = $('CHECKBOX').val();
...
...
if (CHECKBOX.checked == FALSE){
var error = true;
$('#notchecked_error').fadeIn(500);
}else{
$('#notchecked_error').fadeOut(500);
}
Try using:
if ( $('#CHECKBOX').prop("checked") )
or:
if ( $('#CHECKBOX').is(":checked") )
Also, be sure your selector for the checkbox is correct.
I see two problems in your code. The first one is that the selector in your CHECKBOX assignation is faulty. It should be
var CHECKBOX = $('#CHECKBOX').val();
or
var CHECKBOX = $('input[type=checkbox]').val();
the second problem is that you are reading CHECKBOX.checked from the val() function, you need to read it from the checkbox itself.
if(CHECKBOX.checked)
$('input[type=checkbox]:checked') // If you have multiple checkboxes you can use this and loop through them to get additional info
$('#checkboxID:checked').length // To get one specific checkbox
`$('CHECKBOX').val();`
Will try to find an element with a tagname of CHECKBOX and return it's value. Presumably you want to reference the checkbox with an ID of CHECKBOX:
var CHECKBOX = $('#CHECKBOX');
To see if it's checked:
if (!CHECKBOX[0].checked) {
// CHECKBOX is not checked
}
You really should learn basic javascript before using jQuery. Usually validation is initiated from a form submit, which can give you are reference to the form. You can then reference all of the form elements as properties of the form, you don't need to create all of those jQuery objects. e.g. if you form is something like:
<form ... onsubmit="validate(this)"... >
<input type="checkbox" name="checkbox">
</form>
Then in your validate function:
function validate(form) {
if (!form.checkbox.checked) {
// the checkbox isn't checked
}
}
You can attach the listener dynamically if you wish.

Categories

Resources