I am changing state of check boxes with following code:
document.getElementById('checkall').onclick = function(){
inputs = VARIABLE.querySelectorAll('input[type=checkbox]');
for(i=0; i<inputs.length; i++)
inputs[i].checked = true;
}
This section work fine.
and i am creating checkboxes with(these codes call on for):
mainFrameInput = document.createElement("input"); mainFrameInput.className = "item"; mainFrameInput.style.display='none'; mainFrameInput.setAttribute('type', 'checkbox'); mainFrameInput.setAttribute('id', GnId);
this section work fine too
At this time i want to have a function which run when check boxes changed because it can change on several way.
I am creating check boxes with JavaScript and want to handle onchange with JavaScript NOT JQUERY.
I tested CHECKBOX_VARIABLE.onchange = function{} but it does not call when i change with above code and just CHECKBOX_VARIABLE.onclick work when i click on each checkbox.
I found solution and posted as answer.
one way to do this is by using the native onchange attribute and give it a function
<select id="mySelect" onchange="alert('change')">
<option value="Audi">Audi</option>
<option value="BMW">BMW</option>
<option value="Mercedes">Mercedes</option>
<option value="Volvo">Volvo</option>
</select>
here's a fiddle showing this
https://jsfiddle.net/r4aj8zh2/
You can do this like that:
HTML:
<button id="checkall">check all</button><br>
a: <input type="checkbox" name="a" value="a"><br>
b: <input type="checkbox" name="b" value="b"><br>
c: <input type="checkbox" name="c" value="c">
JavaScript:
var inputs = document.querySelectorAll('input[type=checkbox]');
document.getElementById('checkall').onclick = function(){
for(var i=0; i<inputs.length; i++) {
inputs[i].checked = true;
}
somethingChanged();
}
for(var i=0; i<inputs.length; i++) {
inputs[i].addEventListener('change', somethingChanged);
}
function somethingChanged(evt) {
if (evt) {
console.log(evt.srcElement.name, 'changed');
}
else {
console.log('all changed');
}
}
Fiddle: https://jsfiddle.net/1m3rcvw9/
Explanation: When I tried it I could reproduce your problem - the change listener was not called when clicking the check-all button. So my idea is to just call the function manually after a click occurs on check-all. You can even distinguish between single checkbox clicks and check-all clicks by checking if there is a event-parameter.
EDIT: If you dynamically add <input> tags then just add the somethingChanged change listener right after creation of new elements and update the inputs variable by reselecting all checkboxes:
mainFrameInput = document.createElement("input");
mainFrameInput.addEventListener('change', somethingChanged);
// ... insert the element into DOM here
inputs = document.querySelectorAll('input[type=checkbox]');
You can addEventListener to these checkboxes
// Get all checkbox. Use more specific selector using name or class
var getAllCheckBox = document.querySelector('input[type=checkbox]');
// Adding event listener change to each checkbox
getAllCheckBox.addEventListener('change', function (event) {
if (getAllCheckBox.checked) {
// do something if checked
} else {
// do something else otherwise
}
});
Add event listener to element when element is created. Make sure the D is lower case d at .getElementById VARIABLE = document.getElementById('#div-id');
mainFrameInput = document.createElement("input");
mainFrameInput.addEventListener("change", function() {
// do stuff
})
FINALLY I RESOLVED THE ISSUE:
first of all i developed a function:
function fireEvent(element,event){
if (document.createEventObject){
var evt = document.createEventObject();
return element.fireEvent('on'+event,evt)
}
else{
var evt = document.createEvent("HTMLEvents");
evt.initEvent(event, true, true ); // event type,bubbling,cancelable
return !element.dispatchEvent(evt);
}
}
and called that when changed state of check box:
fireEvent(inputs[i],'change');
and added on change event when creating check boxes:
mainFrameInput.onchange = function(){
if (this.checked)
{
console.log('checked');
}
else
{
console.log('un checked');
}
}
I think it is more easy just define a onchange function into the input element like this:
const wrapperElement = document.querySelector('.wrapper')
const fruits = ['apple', 'orange', 'banana']
fruits.forEach(f => {
const item = document.createElement('div')
item.className = 'item'
const fruit = document.createElement('input')
fruit.type = 'checkbox'
fruit.id = f
fruit.onchange = handleOnChange
const label = document.createElement('label')
label.className = 'checkbox-label'
label.setAttribute('for', f)
label.textContent = f
item.append(fruit)
item.append(label)
wrapperElement.append(item)
})
function handleOnChange(e) {
const element = e.srcElement
element.parentElement.classList.toggle('checked')
}
.item.checked {
background: red;
}
<div class="wrapper"></div>
Related
I have created a checkbox directly in javascript, and binded a click event the following way :
let checkBox = document.createElement('input');
checkBox.onclick = (e) => {
console.log("click", e);
};
Now I would like to convert this element to plain html, while keeping the associated event. I now I can call checkBox.outerHTML to get the associated html, but the event would disappear.
Is there a way to do the same thing without removing the attached event ?
I don't know why would you need such an approach when you simply can append that element where ever you want. Yet, it is still simple to just fix it the way it is.
Instead of assigning an event, you should assign an attribute like this:
const checkBox = document.createElement('input');
checkBox.setAttribute("onclick", "cbxClicked(event)");
function cbxClicked(e) {
console.log("click", e);
};
console.log(checkBox.outerHTML); // <input onclick="cbxClicked(event)">
Tested well on chrome.
The recommended way is this
window.addEventListner("load",function() {
document.getElementById("checkboxContainer")
.addEventListener("click",function(e) {
const tgt = e.target;
if (tgt.type && tgt.type==="checkbox") {
console.log("click",tgt)
}
});
});
Now you can create your checkboxes before or after load
window.addEventListener("load", function() {
const container = document.getElementById("checkboxContainer");
container.addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.type && tgt.type === "checkbox") {
console.log("click", tgt)
}
});
const inp = document.createElement("input")
inp.type = "checkbox";
inp.value = "dynamic";
container.appendChild(inp);
});
<div id="checkboxContainer">
<input type="checkbox" value="static" />
</div>
I know it's easy to do using < button > or < input type="submit" but how would you keep this button disabled unless both input fields are filled?
<input id="one" type="text">
<input id="two" type="text">
OK
Tie an event to both inputs, and check that both have values. Then enable the link.
$('#one, #two').blur(function() {
if($('#one').val() !== "" && $('#two').val() !== "") {
$('.button').attr('href','#');
} else {
$('.button').removeAttr('href');
}
});
and change your html to:
<a class="button">OK</a>
so that the link is disabled on page load. Here's a JSFiddle demo.
$(document).ready(function() {
$inputs = $('#one,#tow');
$inputs.change(check);
$submit = $('#submit');
function check() {
var result = 1;
for (var i = 0; i < $inputs.length; i++) {
if (!$inputs[i].value) {
result = 0;
break;
}
}
if (result) {
$submit.removeAttr('disabled');
} else {
$submit.attr('disabled', 'disabled');
}
}
check();
});
suggest use angular form
$(document).ready(function(){
//$(".button").attr('disabled', "disabled");
$(".button").click(function(){
one = $("#one").val();
two = $("#two").val();
if(one && two){
///both fields filled.
return true;
}
//one or both of them is empty
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="one" type="text">
<input id="two" type="text">
OK
This is my implementation if facing this kind of situation.
First, am add disabled class onto anchor tag on page load by using this style :
.disabled {
color : gray // gray out button color
cursor : default; // make cursor to arrow
// you can do whatever styling you want
// even disabled behaviour
}
We add those class using jquery on document ready together with keyup event like so :
$(function () {
// add disabled class onto button class(anchor tag)
$(".button").addClass('disabled');
// register keyup handler on one and two element
$("#one, #two").keyup(function () {
var one = $("#one").val(),
two = $("#two").val();
// checking if both not empty, then remove class disabled
if (one && two) $(".button").removeClass('disabled');
// if not then add back disabled class
else $(".button").addClass('disabled');
});
// when we pressing those button
$('.button').click(function (e) {
// we check if those button has disabled class yet
// just return false
if ($(this).hasClass('disabled')) return false;
});
});
DEMO
I've got a problem. I must create a form with five check-boxes.
The user must select exactly three of the five check-boxes.
At the time of change check-box updates the marker at check-box
When the user presses a fourth element should light up at the red light.
3. When you deselect any item marker when it disappears (is white) and the rest are green.
Here is what I'm done: http://jsfiddle.net/epredator/98TfU/
and some of my code, because I can't post a JSfiddle link without some code in text ;):
function checkGreen() {
if (this.checked && counter >= 3) {
console.log("if test in checkGreen()");
}
}
I've got a problem with point 3, because i don't know how to change red light to green after uncheck one of check-boxes with green light. I spend a lot of time on it. As you can see I am not the master of Javascript and ask you for help, pleas help me :) ... and for the end i must use pure JavaScript (no jQuery). Thanks a lot for help ...
Here is how I would do it. It is cleaner than how you were doing it before. FIDDLE. Keep an array of the checked boxes, and use it to determine which ones should be what color.
(function() {
var checked = [];
document.getElementById("Checkbox1").addEventListener("click",toggle);
document.getElementById("Checkbox2").addEventListener("click",toggle);
document.getElementById("Checkbox3").addEventListener("click",toggle);
document.getElementById("Checkbox4").addEventListener("click",toggle);
document.getElementById("Checkbox5").addEventListener("click",toggle);
function toggle() {
if (this.checked) {
checked.push(this);
} else {
var index = checked.indexOf(this);
var box = checked.splice(index,1)[0];
box.nextElementSibling.className = "white";
}
refresh();
}
function refresh() {
for (var i = 0; i < checked.length; i++) {
if (i < 3) {
checked[i].nextElementSibling.className = "green";
} else {
checked[i].nextElementSibling.className = "red";
}
}
}
}());
For Javascript, you can use below code
<script type="text/javascript">
// method to bind handler
function bindEvent(element, type, handler) {
if (element.addEventListener) {
element.addEventListener(type, handler, false);
} else {
element.attachEvent('on' + type, handler);
}
}
// binding click event to all the checkboxes with name 'choice'
// you can generalize this method
window.onload = function () {
var elements = document.getElementsByName('choice');
if (!elements)
return;
for (var i = 0; i < elements.length; i++) {
var ele = elements[i];
bindEvent(ele, 'click', function () {
changeColor();
});
}
}
// Pass the checkbox name to the function
// taken from stack overflow answer
//http://stackoverflow.com/questions/8563240/how-to-get-all-checked-checkboxes
function getCheckedBoxes(chkboxName) {
var checkboxes = document.getElementsByName(chkboxName);
var checkboxesChecked = [];
// loop over them all
for (var i = 0; i < checkboxes.length; i++) {
// And stick the checked ones onto an array...
if (checkboxes[i].checked) {
checkboxesChecked.push(checkboxes[i]);
}
}
// Return the array if it is non-empty, or null
return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}
// with your other function, you can call this function or club the functionality
function changeColor() {
var elements = document.getElementsByName('choice');
if (!elements)
return;
var selectedCheckBoxes = getCheckedBoxes('choice');
if (selectedCheckBoxes && selectedCheckBoxes.length == 3) {
// set color to green
}
}
</script>
and HTML used as: (note only 'name' property from input element)
<span>
<input type="checkbox" name="choice" id="Checkbox1" />1</span>
<span>
<input type="checkbox" name="choice" id="Checkbox2" />2</span>
<span>
<input type="checkbox" name="choice" id="Checkbox3" />3</span>
<span>
<input type="checkbox" name="choice" id="Checkbox4" />4</span>
<span>
<input type="checkbox" name="choice" id="Checkbox5" />5</span>
You can get all the checked elements and if the count is 3, mark every body with interested color.
I have a code that can show div everytime I click a radio button and it is working fine. The problem is I want all the radio button be checked and then the div will show.
Here is my code for 1 radio button
function showstuff(nxt){
document.getElementById(nxtb).style.display="block";
}
<input id="ny" name="ny" type="radio" onClick="document.getElementById('ny').checked =
true; showstuff('nxt');" />
<div id="nxtb">Next</div>
Thanks in advance
Here is a solution without an obtrusive JavaScript (that is onclick attributes):
/*
* Convert to array so we can use `forEach()` and `every()`
*/
function toArray(any) {
return Array.prototype.slice.call(any);
}
var observed = toArray(document.querySelectorAll('[data-observe]'));
var listened = [];
var result = document.querySelector('#result');
/*
* Gather all elements we want to listen for change:
* observed elements and their siblings with the same name
*/
observed.forEach(function (target) {
var siblings = toArray(document.querySelectorAll('[name=' + target.name +']'));
listened = listened.concat(siblings);
});
listened.forEach(function (radio) {
radio.addEventListener('change', function () {
var checked = observed.every(function (item) {
return item.checked;
});
checked ?
result.removeAttribute('hidden') :
result.setAttribute('hidden', 'true');
});
});
Demo: http://jsfiddle.net/sZHAA/1/
I am using the following script to set my colors:
<script type="text/javascript">
if (localStorage.buttonColor) {
document.getElementsByTagName('html')[0].className = localStorage.buttonColor
}
function getButtonColor(buttonName) {
localStorage.buttonColor = buttonName;
document.getElementsByTagName('html')[0].className = buttonName
}
</script>
Here's my HTML:
<form class="ng-pristine ng-valid">
<button name="darkBlue" onclick="getButtonColor(this.name)">Blue</button>
<button name="black" onclick="getButtonColor(this.name)">Black</button>
</form>
How can I make it so that when a color is chosen that the button to select that color is
disabled so that It cannot be selected again? Then when another button is clicked the other(s) are enabled. Also I need to set the button that's chosen from localstorage to disabled. Sorry I didn't not mention this fully in the question earlier.
function getButtonColor(button) {
button.disabled = "disabled"
localStorage.buttonColor = button.name;
document.getElementsByTagName('html')[0].className = button.name
}
and simply send this:
<button name="darkBlue" onclick="getButtonColor(this)">Blue</button>
<button name="black" onclick="getButtonColor(this)">Black</button>
<disclaimer> inline javascript is evil</disclaimer>
In addition to other answers (just send the button in the handler), you can use this when initially setting the color from localStorage (assuming your 'form' is the first child of 'body'):
if (localStorage.buttonColor) {
document.getElementsByTagName('html')[0].className = localStorage.buttonColor
var buttons = document.body.getElementsByTagName('form')[0].getElementsByTagName('button')
for(var i =0; i < buttons.length; i++)
if(buttons[i].name == localStorage.buttonColor) button.disabled = true
}
Although you might want to consider using jQuery if you often need to find elements in your code, since the getElementsByTagName selections can get verbose.
You can also use :
function getButtonColor(button) {
var elem=documentt.getElementById(button.id);
elem.removeAttribute("onclick");
}
Preferred is to use this and bind it to a variable (often that).
In this you get the html-object who called the function.
http://www.quirksmode.org/js/this.html
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
function getButtonColor() {
var that = this;
localStorage.buttonColor = that.Name;
document.getElementsByTagName('html')[0].className = that.Name;
that.disabled = "disabled";
}