How to uncheck a checkBox but stop any event from getting fired? - javascript

I have a onclick function attached to check Box (which selectes or Unselects all dependent checkBoxes),I am using AngularJs. So For a checkBox say X ,there are more dependant chekcboxes say A ,B ,C. So when all of the get checked X get checked automatically. And when even one of the get unchekced X get unchekced. But I need to stop "Unselecting checkBox event" from getting fired.
Is there any way possible to do that?
<span style="float: right">
<input id="SelectAllRecords" type="checkbox" ng-model="toSelectAllEmployees"
ng-click="selectAndAddAllEmployees($event)">{{selectAllLabel}} {{totalRecord()}}
</span>
$scope.$watch('toSelectAllEmployees',function() {
// toSelectAllEmployees is an ng-model for select all Emp
if($scope.toSelectAllEmployees!=null && $scope.toSelectAllEmployees!=undefined) {
$scope.selectAllOrUnselectAll();
}
});
$scope.selectAllOrUnselectAll = function() {
if($scope.toSelectAllEmployees!=null && $scope.toSelectAllEmployees!=undefined) {
if($scope.toSelectAllEmployees==true) {
$('.allEmployees').attr("checked", true);
} else {
$(".allEmployees").attr('checked',false);
if($rootScope.fromMovingPage!=2 && $rootScope.fromMovingPage!=3) {
// as we have now unchecked all employees hence we need to do matching and selected employee list size 0
$scope.matchingAndSelectedEmployeesList.length = 0;
}
}
}
}

in the onclick event, providing you pass an event var like
function(e) {
}
you may type:
function(e) {
e.preventDefault();
}
I believe this is what you are asking.

Related

Angularjs click clear button inside input but no effect to binded json object

As title. I have a page with several inputs with type="text", and set them with clear buttons generated by the js code:
function SetClearButtonInTextBox(Callback) {
if (!window.document.documentMode) {
$("input").each(function () {
var im = $(this);
if (!$(this).parent().hasClass("text-input-wrapper") && !$(this).hasClass("btn")) {
$(this).wrap("<div class='text-input-wrapper'></div>");
$(this).after("<button class=\"Covered\" type=\"button\">×</button>");
}
$(this).closest("div.text-input-wrapper").find("button").mousedown(function () {
im.val("");
im.change();
//return false;
});
});
}
}
And my inputs like this:
<input name="ModelA" ng-model="dl.ModelA" ng-change="ClearText(this,dl.ModelA);" value=""/>
<input name="ModelB" ng-model="dl.ModelB" ng-change="ClearText(this,dl.ModelB);" value=""/>
And I made the "ClearText" function as:
$scope.ClearText=function(target, ngModelTo){
if (target.target.value == "") {
ngModelTo = "";
}
}
I want when I click the clear button inside input, the binded value and the textbox will also be cleared, but I found that only my textbox is cleared but the binded value isn't.
Could someone guide me to make it?

Disable and enable function in Jquery

I have a text input in html that is affected by a function exectued by .change() events from different radios and checkboxes. I'm trying to make it so that if a user types into the input, this function will no longer run when a .change() event happens in the aforementioned radios and checkboxes (the user must still be able to use these radios and checkboxes). However, if the user leaves the input blank and clicks away, the script will run again. I hope is possible.
Here is my take on this so far:
Using.prop('diabled' isnt viable because it completely disables the input, making the user unable to type in it, so I need another solution.
$(function() {
$('#burger-navn').on('input', function() {
$("#burger-navn").prop('disabled', true);
});
//When the input (#burger-navn) is typed into it should be "disabled"
$('#burger-navn').focusout(function() {
if ($(this).val().length == 0) {
$("#burger-navn").prop('disabled', false);
}
});
//But if its clicked out of while its blank, it should be able to run again.
$("#okseinput, #laksinput, #kyllinginput, #vegetarinput").change(function() {
if (!$("#burger-navn").not(':disabled')) { //condition that tests
navngenerator();
}
});
});
To solve this I simply created a separate input tag that I could add and remove disabled attribute from, and check if it has that attribute.
So in html:
<input id="burger-navn" type="text"/>
<input id="toggle" disabled="disabled" style="display:none"/>
jQuery:
var previousValue = $("#burger-navn").val();
$("#burger-navn").keyup(function(e) {
var currentValue = $(this).val();
if(currentValue != previousValue) {
previousValue = currentValue;
$("#toggle").prop('disabled', false);
}//This function will remove disabled from #toggle, when a user types into #burger-navn
});
$('#burger-navn').focusout(function() {
if ($(this).val().length == 0) {
$("#toggle").prop('disabled', true);
}
});
if ($("#toggle").is(':disabled')) {
navngenerator();
}
$("#okseinput, #laksinput, #kyllinginput, #vegetarinput").change(function() {
if ($("#toggle").is(':disabled')) {
navngenerator();
}
});
$(selector).on('change', function(event){
event.preventDefault();
event.stopPropagation();
// the selected field no longer does anything on change
});
is that what you are looking for?

jQuery/Javascript Checkbox

i want do something like this with a checkBox. if the user clicks on the checkbox, it should change its state (checked -> unchecked and vv. ).
my code:
$('#checkBoxStandard').change(function() {
clickedFormBoxen('standard');
});
function clickedFormBoxen(active){
if(active == 'standard'){
if( $('#checkBoxStandard').is(":checked")){
$('#checkBoxStandard').prop("checked", false);
}else{
$('#checkBoxStandard').prop("checked", true);
}
console.log('ac: '+$('#checkBoxStandard').is(':checked'));
}
Unfortunately, the checkbox will not be unchecked again. The fist time, the checkbox is getting checked, but if i click on it again, nothing happens, it's still checked.
I wish to use this code so i can change the state of the checkbox by function call and not just by user interaction.
Please help me and sorry for my english^^
Try
$('#checkBoxStandard').removeAttr("checked");
You mean something like this? (jsFiddle)
HTML
<input type="checkbox" id="checkbox">
<label for="checkbox">Hey,check me!</label>
JavaScript
var respond = true;
function manualCheck(state)
{
respond = false;
$('#checkbox').prop("checked", state);
}
$('#checkbox').change(function ()
{
if (!respond)
{
respond = true;
return;
}
// Your code
}
As i've mentionend in my comment to your question, with your function clickedFormBoxen you effectively revert the effect of a user interaction on the checkbox element. Thus it seems that you have to call the change handler from a click handler on your checkbox element (i've streamlined the code a bit):
function clickedFormBoxen(active) {
if (active == 'standard') {
$('#checkBoxStandard').prop("checked", !($('#checkBoxStandard').prop("checked")));
}
}
$(document).ready( function(){
$('#checkBoxStandard').change( function(e) {
clickedFormBoxen('standard');
1;
});
$('#checkBoxStandard').click(function(e) {
$('#checkBoxStandard').change();
1;
});
});

Why isn't jquery detecting when a radio button is unchecked? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JQuery $(#radioButton).change(…) not firing during de-selection
I have the following HTML/jQuery:
<input id="rb1" type="radio" name="rb" checked="true">
<input id="rb2" type="radio" name="rb">
$("#rb2").change(function () {
if ($(this).is(":checked")) {
alert('checked');
}
else {
alert('unchecked');
}
});
When my rb2 radio button is unselected by selecting rb1, the change event does not fire. Why is this? Is it possible to get this working without changing my selector to match both inputs and then looking at the ID?
Fiddle: http://jsfiddle.net/4uRWR/
The change event only gets sent when you actually modify the item itself. When you click the other radio, you aren't modifying it. A fix would be to watch the change event on every input:radio, then just check the state of the relevant radio button:
$("input:radio").change(function () {
if ($("#rb2").is(":checked")) {
alert('checked');
}
else {
alert('unchecked');
}
});
http://codepen.io/AlienHoboken/pen/akwjB
Listen for change on every input related to your group of radios and then check if a specific one is selected.
$("input[name=rb]").change(function () {
if ($('#rb2').is(":checked")) {
alert('checked');
} else {
alert('unchecked');
}
});
http://jsfiddle.net/4uRWR/2/
You can artificially trigger a "change" on radio buttons from the same group so that the original bound handler would get picked up and output "unchecked". The trick is to avoid being stuck in an infinite loop by recursively re-triggering the event, we can avoid that by ignoring artificial events that lack the originalEvent property:
$("input[type=radio]").on("change", function (e) {
var $this = $(this);
//all inputs with the same name
var $targetInputSelector = $("input[name=" + $this.attr("name") + "]");
//check if the handler was fired "naturally"
//if yes, trigger the change handler "artificially" for inputs with the same name
if (e.hasOwnProperty('originalEvent')) {
//exclude the element that was changed "naturally"
//from the subset of all the elements with the same name
$targetInputSelector.not($this).triggerHandler("change");
}
});
This code works when added on top of your current handler and satisfies the without changing my selector to match both inputs and then looking at the ID criteria ;)
http://jsfiddle.net/a73tn/24/
I sorta ran into this issue a few days ago. Instead of listening for an individual click on a radio button, I listen for a click on the <ul> I have them in and then call this function to check if one has been selected.
// Iterate over the radio group and determine if one of them is selected
function loopRadBtns(btnGroup)
{
var isChecked = false;
btnGroup.find('input[type="radio"]').each(function()
{
if($(this).attr('checked'))
{
isChecked = true;
}
});
return isChecked;
}

Check/Uncheck checkbox with JavaScript

How can a checkbox be checked/unchecked using JavaScript?
Javascript:
// Check
document.getElementById("checkbox").checked = true;
// Uncheck
document.getElementById("checkbox").checked = false;
jQuery (1.6+):
// Check
$("#checkbox").prop("checked", true);
// Uncheck
$("#checkbox").prop("checked", false);
jQuery (1.5-):
// Check
$("#checkbox").attr("checked", true);
// Uncheck
$("#checkbox").attr("checked", false);
Important behaviour that has not yet been mentioned:
Programmatically setting the checked attribute, does not fire the change event of the checkbox.
See for yourself in this fiddle:
http://jsfiddle.net/fjaeger/L9z9t04p/4/
(Fiddle tested in Chrome 46, Firefox 41 and IE 11)
The click() method
Some day you might find yourself writing code, which relies on the event being fired. To make sure the event fires, call the click() method of the checkbox element, like this:
document.getElementById('checkbox').click();
However, this toggles the checked status of the checkbox, instead of specifically setting it to true or false. Remember that the change event should only fire, when the checked attribute actually changes.
It also applies to the jQuery way: setting the attribute using prop or attr, does not fire the change event.
Setting checked to a specific value
You could test the checked attribute, before calling the click() method. Example:
function toggle(checked) {
var elm = document.getElementById('checkbox');
if (checked != elm.checked) {
elm.click();
}
}
Read more about the click method here:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click
to check:
document.getElementById("id-of-checkbox").checked = true;
to uncheck:
document.getElementById("id-of-checkbox").checked = false;
We can checked a particulate checkbox as,
$('id of the checkbox')[0].checked = true
and uncheck by ,
$('id of the checkbox')[0].checked = false
Try This:
//Check
document.getElementById('checkbox').setAttribute('checked', 'checked');
//UnCheck
document.getElementById('chk').removeAttribute('checked');
I would like to note, that setting the 'checked' attribute to a non-empty string leads to a checked box.
So if you set the 'checked' attribute to "false", the checkbox will be checked. I had to set the value to the empty string, null or the boolean value false in order to make sure the checkbox was not checked.
Using vanilla js:
//for one element:
document.querySelector('.myCheckBox').checked = true //will select the first matched element
document.querySelector('.myCheckBox').checked = false//will unselect the first matched element
//for multiple elements:
for (const checkbox of document.querySelectorAll('.myCheckBox')) {
//iterating over all matched elements
checkbox.checked = true //for selection
checkbox.checked = false //for unselection
}
function setCheckboxValue(checkbox,value) {
if (checkbox.checked!=value)
checkbox.click();
}
<script type="text/javascript">
$(document).ready(function () {
$('.selecctall').click(function (event) {
if (this.checked) {
$('.checkbox1').each(function () {
this.checked = true;
});
} else {
$('.checkbox1').each(function () {
this.checked = false;
});
}
});
});
</script>
For single check try
myCheckBox.checked=1
<input type="checkbox" id="myCheckBox"> Call to her
for multi try
document.querySelectorAll('.imChecked').forEach(c=> c.checked=1)
Buy wine: <input type="checkbox" class="imChecked"><br>
Play smooth-jazz music: <input type="checkbox"><br>
Shave: <input type="checkbox" class="imChecked"><br>
If, for some reason, you don't want to (or can't) run a .click() on the checkbox element, you can simply change its value directly via its .checked property (an IDL attribute of <input type="checkbox">).
Note that doing so does not fire the normally related event (change) so you'll need to manually fire it to have a complete solution that works with any related event handlers.
Here's a functional example in raw javascript (ES6):
class ButtonCheck {
constructor() {
let ourCheckBox = null;
this.ourCheckBox = document.querySelector('#checkboxID');
let checkBoxButton = null;
this.checkBoxButton = document.querySelector('#checkboxID+button[aria-label="checkboxID"]');
let checkEvent = new Event('change');
this.checkBoxButton.addEventListener('click', function() {
let checkBox = this.ourCheckBox;
//toggle the checkbox: invert its state!
checkBox.checked = !checkBox.checked;
//let other things know the checkbox changed
checkBox.dispatchEvent(checkEvent);
}.bind(this), true);
this.eventHandler = function(e) {
document.querySelector('.checkboxfeedback').insertAdjacentHTML('beforeend', '<br />Event occurred on checkbox! Type: ' + e.type + ' checkbox state now: ' + this.ourCheckBox.checked);
}
//demonstration: we will see change events regardless of whether the checkbox is clicked or the button
this.ourCheckBox.addEventListener('change', function(e) {
this.eventHandler(e);
}.bind(this), true);
//demonstration: if we bind a click handler only to the checkbox, we only see clicks from the checkbox
this.ourCheckBox.addEventListener('click', function(e) {
this.eventHandler(e);
}.bind(this), true);
}
}
var init = function() {
const checkIt = new ButtonCheck();
}
if (document.readyState != 'loading') {
init;
} else {
document.addEventListener('DOMContentLoaded', init);
}
<input type="checkbox" id="checkboxID" />
<button aria-label="checkboxID">Change the checkbox!</button>
<div class="checkboxfeedback">No changes yet!</div>
If you run this and click on both the checkbox and the button you should get a sense of how this works.
Note that I used document.querySelector for brevity/simplicity, but this could easily be built out to either have a given ID passed to the constructor, or it could apply to all buttons that act as aria-labels for a checkbox (note that I didn't bother setting an id on the button and giving the checkbox an aria-labelledby, which should be done if using this method) or any number of other ways to expand this. The last two addEventListeners are just to demo how it works.
I agree with the current answers, but in my case it does not work, I hope this code help someone in the future:
// check
$('#checkbox_id').click()

Categories

Resources