how to set checkbox checked and do it onclick together? - javascript

My code is only let checkbox checked,I want it also do onclick event.
<input type="checkbox" name="list" id="mycheckbox" onclick="check_marker(this)" />
document.getElementById(mycheckbox).checked = true;//I want also do onclick event.
function check_marker(input_var){
var carId;
carId = input_var.id;
alert(carId);
}

Changes made through javascript do not trigger handlers. You will need to call it yourself after making the change:
http://jsfiddle.net/F2J37/
var cb = document.getElementById("mycheckbox");
cb.checked = true;
cb.onclick(); // call the click handler directly

Related

i want to push checked checkboxes and don't send unchecked checkboxes(pure javascript)

how can i push all checked checkboxes to array
You can pass function reference to html and track it.
<input type="checkbox" onchange="handleChange(event)">
JS:
function handleChange(e) {
const {checked} = e.target;
}
I suppose what you want is add an event listener to your new checkbox.
After cell.appendChild(element1);, you can add an event listener as follow:
element1.addEventListner('click', () => {
toggleThisNumber(0);
// your other codes here
});

Javascript click event firing twice, even with stopPropagation

I have a set of items like this:
<label for="Cadenza-1" class="cars">
<input type="checkbox" value="1" alt="Cadenza" id="Cadenza-1" name="vehicles[]">
<img src="img/bill_murray_173x173.jpg">
<span>Cadenza</span>
</label>
there's about 13 of them. I want to add a class to the label when clicked. However, the click event fires twice. right now I'm debugging the click event then I'll add the class:
var cars = document.getElementsByClassName('cars');
for(var c = 0;c < cars.length; c++){
cars[c].addEventListener("click", function(e){
selectVehicle(cars[c],e);
},false);
}
function selectVehicle(el,e) {
console.log(e);
e.stopPropagation();
}
The console.log fires twice.
Try adding preventDefault after your stopPropogation:
function selectVehicle(el,e) {
console.log(e);
e.stopPropagation();
e.preventDefault();
}
I believe it is best to place console.log(e) after the stopPropogation & preventDefault though. You will also then need to implement functionality to set the checkbox to checked since this would prevent that from happening.
When the <span> or the <img> receives a "click" event, that'll bubble up the DOM to the <label> element, and your event handler will be called. The <label> then triggers another "click" event on the <input> element, and that also bubbles up to the <label>.
You can check in the handler to see whether the <input> was clicked:
function selectVehicle(el,e) {
if (e.target.tagName !== "INPUT") return;
// do stuff
}
Alternatively, you could just add the "click" handler only to the <input> itself.
Now you're also going to notice that your code isn't working because you've hit a common problem with binding event handlers inside loops. The problem is that the variable c will have as its value the length of the cars list by the time the event handlers actually run. There are a few ways of dealing with that; one is to loop with forEach() instead of a for loop:
[].forEach.call(cars, function(car) {
car.addEventListener("click", function(e){
selectVehicle(car,e);
}, false);
});
You are adding the event listener to the label, you should add the event listener to the checkbox because the label behavior copy the same of the input assigned in for.
Please note that if you click just in the checkbox the callbacks works fine, this is because the event on the label is raised by the checkbox.
The right way to do that is to add the event listener only for the checkbox or adding prevent default in the setlectVehicle callback.
You are not required to preventDefault or stopPropagation, but just to add listner on the input element.
cars[c].children[0].addEventListener("click", function(e) {
Try this. It is working as expected.
Additionally, you are not required to use Id's with label's for if the label element encloses the required input/other elements
var cars = document.getElementsByClassName('cars');
for (var c = 0; c < cars.length; c++) {
cars[c].children[0].addEventListener("click", function(e) {
selectVehicle(cars[c], e);
}, false);
}
function selectVehicle(el, e) {
console.log(e);
}
<label class="cars">
<input type="checkbox" value="1" alt="Cadenza" name="vehicles[]">
<img src="img/bill_murray_173x173.jpg">
<span>Cadenza</span>
</label>
<label class="cars">
<input type="checkbox" value="1" alt="Cadenza" name="vehicles[]">
<img src="img/bill_murray_173x173.jpg">
<span>Cadenza 2</span>
</label>

How to properly clear another field on checkbox click in Knockout.js?

I have a list of checkboxes and one of them is "Other" and what I want is that if "Other" is selected, then a textbox is enabled. If "Other" is not checked, then the textbox must be disabled and its content must be cleared.
Now, the problem is that when I click on the "Other" checkbox, the checkmark doesn't show up or disappear UNTIL I trigger another binding event. I must have on the way of Knockout by adding the click event handler to the "Other" checkbox.
fiddle here
HTML
<input type='checkbox' value='apple' data-bind='checked: selectedFoods' />apple
<br>
<input type='checkbox' value='banana' data-bind='checked: selectedFoods' />banana
<br>
<input type='checkbox' value='other' data-bind='checked: selectedFoods, event: {click: otherClicked}' />other
<input type='text' data-bind="text: otherFoods, attr:{disabled: selectedFoods.indexOf('other') < 0}" />
JS
$(document).ready(function () {
var BaseVM = function () {
var that = {};
return that;
};
var TestVM = function () {
var that = BaseVM();
that.selectedFoods = ko.observableArray(['apple', 'banana']);
that.otherFoods = ko.observable(null);
that.otherClicked = function () {
if (that.selectedFoods.indexOf('other') < 0) {
that.otherFoods = '';
}
};
return that;
};
var vm = TestVM();
ko.applyBindings(vm);
});
This line
that.otherFoods = '';
is wrong. You need to assign the value as an observable, since that's what it is:
that.otherFoods('');
Also, you need to evaluate your array when checking the values:
that.selectedFoods.indexOf('other') < 0
should be
that.selectedFoods().indexOf('other') < 0
Edit: and your click handler was set up wrong, see this updated fiddle:
http://jsfiddle.net/2qdu9tuo/9/
You need to return true in the click handler to let the checkbox still behave like a checkbox. Also, you're using the text binding instead of the value binding on the textbox.
First, you need to return true from your click handler, otherwise the native event would not propagate and the checkbox state will not change.
Also, when resetting the otherFoods observable, you need to invoke the observable, not override it:
that.otherClicked = function () {
if (that.selectedFoods.indexOf('other') < 0)
that.otherFoods('');
return true;
};
Another problem is that you're using the text binding handler, for your otherFoods input, instead of the value handler:
<input type='text' data-bind="value: otherFoods, attr:{disabled: selectedFoods.indexOf('other') < 0}" />
See Fiddle

javascript onload page radio checked

I have a function that enables or disables form elements based on which radio item is checked. It is working ok. However, I wish that one of the radio buttons to be checked at page load with the appropriate form elements already disabled or enabled.
Right now on page load, I have one of the radio buttons checked on the form itself but the javascript will fire when there is a change.
Here is the javascript
<script type="text/javascript">
function customerChoice() {
if (document.getElementById('radio1').checked) {
document.getElementById('company').disabled = false;
document.getElementById('onetime').disabled = true;
document.getElementById('span1').style.color = '#cccccc';
document.getElementById('span2').style.color = '#000000';
}
if (document.getElementById('radio2').checked) {
document.getElementById('company').disabled = true;
document.getElementById('onetime').disabled = false;
document.getElementById('span1').style.color = '#000000';
document.getElementById('span2').style.color = '#cccccc';
}
}
window.onload = customerChoice();
</script>
And here are the two radio buttons.
<input type="radio" name="type" id="radio1" value="C" onclick="customerChoice()" checked />Current Customer<br />
<input type="radio" name="type" id="radio2" value="O" onclick="customerChoice()" />One Time Customer<br />
Need help figuring out what to change in order to make the javascript fire upon loading. Thank you.
Try:
window.onload = customerChoice;
The way you have it runs the function immediately, and sets the onload handler to the result (which is undefined, since the function doesn't return anything), rather than to the function itself. It's not working because it runs before the DOM is loaded.
try putting the customerChoice() function inside an anonymous function:
window.onload = function() {
customerChoice();
};

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