I have three forms, each of them has checkboxes and submit button. I need to get all checkbox names or id by clicking on the submit button in only this form.
And for other two also.
function getCheckedBoxes(item) {
var checkboxes = document.getElementsByName(item);
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
console.log(checkboxes);
return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}
var inp = document.getElementsByName('send');
for(var i = 0; i < inp.length; i++){
inp[i].addEventListener('click', function(e) {
getCheckedBoxes("item");
e.preventDefault();
});
}
example of my checkboxes
<form>
<input id="check29" type="checkbox" name="item" value="29" />
<input class="lab-btn" type="submit" value="ADD ALL" name="send">
</form>
You can pass the form as a parameter to the function, then use querySelectorAll to get all of its inputs with the desired name.
So first, change the event handler to this:
inp[i].addEventListener('click', function(e) {
getCheckedBoxes(this.form, "item");
e.preventDefault();
});
Then the function itself to:
function getCheckedBoxes(oForm, item) {
var checkboxes = oForm.querySelectorAll('input[name="' + item + '"]');
//...
}
To select all checboxes on a page you can use:
var checkboxes = document.querySelectorAll("input[type=checkbox]");
// And for all checkboxes in a form:
var checkboxesInForm = form.querySelectorAll("input[type=checkbox]");
See https://developer.mozilla.org/nl/docs/Web/API/Document/querySelectorAll for documentation.
Does this answer your question?
Related
I am new to web developing. Apologies, if this is too simple but could not find the right way to fix this issue.
I have been asked to make a simple form with several checkboxes having a unique name and different values.
No problem for that. The issue I am encountering is that I have also been asked that I need to have all the checkboxes checked by default before submission and only to keep the checkboxes that remain checked, checked after the form submission. My code below does not make them all checked by default but save the results after form submission. Even adding the statement checked on the input tag does not change much.
<form onsubmit="return saveCheckboxValue();">
<label for="checkbox1">Option 1</label>
<input type="checkbox" id="checkbox1">
<br>
<label for="checkbox2">Option 2</label>
<input type="checkbox" id="checkbox2">
<br>
<label for="checkbox3">Option 3</label>
<input type="checkbox" id="checkbox3">
<br>
<input type="submit" value="Submit">
</form>
<script>
function saveCheckboxValue() {
// Get all checkbox elements
var checkboxes = document.querySelectorAll("input[type='checkbox']");
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
localStorage.setItem(checkboxes[i].id, true);
} else {
localStorage.removeItem(checkboxes[i].id);
}
}
return true;
}
window.onload = function() {
// Get all checkbox elements
var checkboxes = document.querySelectorAll("input[type='checkbox']");
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = JSON.parse(localStorage.getItem(checkboxes[i].id)) || false;
}
};
</script>
I tried to change the value to true
> window.onload = function() { // Get all checkbox elements var
> checkboxes = document.querySelectorAll("input[type='checkbox']");
>
> for (var i = 0; i < checkboxes.length; i++) {
> checkboxes[i].checked = JSON.parse(localStorage.getItem(checkboxes[i].id)) || true; } };
But by doing this, the checkboxes will be checked by default which is good, but if I uncheck some and submit the form, even the unchecked ones will be checked after the form submission.
From what I understood you want the boxes to be checked by default only at the first load, then the values to be persistent.
Would that work for you ?
in the saveCheckboxValue function, change the else condition to set the item to false instead of deleting it.
window.onload = function () {
// Get all checkbox elements
var checkboxes = document.querySelectorAll("input[type='checkbox']");
var val;
for (var i = 0; i < checkboxes.length; i++) {
val = JSON.parse(localStorage.getItem(checkboxes[i].id))
if (val == null) {
checkboxes[i].checked = true;
} else{
checkboxes[i].checked = val;
}
}
};
I am having dynamically created checkbox...
I want that checked value from the checkbox should be stored in one array...
I am Facing the following Problems...
*
var checkedvalue=document.querySelectorAll('input[type=checkbox]:checked');
If I alert the value of checkedvalue It given undefined
If I have console.log the final variable console.log(array); It given the
["on"] in the console.log if the value is checked.
I didn't get the actual value.My code is given below. I don't know what is the mistake I did. Anyone could you please help me.
Thanks in Advance
<input type="Submit" Value="add" onclick="searchinput()">
--------------
function searchinput()
{
var li=document.createElement("li");
//creating checkbox
var label=document.createElement('label');
label.className="lab_style";
li.appendChild(label);
var check=document.createElement('input');
check.type="checkbox";
check.name="check_bo";
li.appendChild(check);
check.addEventListener('click', function() {
var array=[];
var checkedvalue=document.querySelectorAll('input[type=checkbox]:checked');
alert(checkedvalue.value);
for (var i = 0; i < checkedvalue.length; i++) {
array.push(checkedvalue[i].value);
console.log(array);
}
}, false);
}
one of the problems you are facing is that
document.querySelectorAll('input[type=checkbox]:checked');
returns a NodeList and value is not a property on an NodeList object. That is why you are seeing "undefined" in your alert.
Changing as little of your code as possible, I think this should work:
function searchinput()
{
var li=document.createElement("li");
//creating checkbox
var label=document.createElement('label');
label.className="lab_style";
li.appendChild(label);
var check=document.createElement('input');
check.type="checkbox";
check.name="check_bo";
li.appendChild(check);
check.addEventListener('click', function() {
var array=[];
var checkedvalue = document.querySelectorAll('input[type=checkbox]:checked');
for (var i = 0; i < checkedvalue.length; i++) {
if(checkedvalue[i].checked) {
array.push(checkedvalue[i].value);
}
}
}, false);
}
If you have a form with a bunch of checkboxes and once the form is submitted you want to have the values of all the checkboxes which are checked stored in an array then you can do it like this.
const checkboxes = document.querySelectorAll("input[type=checkbox]");
const form = document.querySelector("form");
const arr = [];
form.addEventListener("submit", (e) => {
e.preventDefault()
checkboxes.forEach(chbox => {
if (chbox.checked) {
arr.push(chbox.value)
}
})
console.log(arr)
})
<form>
<label>Apple:
<input type="checkbox" value="apple" name="test"></label>
<label>Mango:
<input type="checkbox" value="mango" name="test"></label>
<label>Banana:
<input type="checkbox" value="banana" name="test"></label>
<label>Grape:
<input type="checkbox" value="grape" name="test"></label>
<button type="submit">Submit</button>
</form>
I want the checked checkboxes to be unchecked when clicking another button:
Below is the HTML
<input type="checkbox" name="checkb" id="Agent" value="Agent"> type=Agent
<br />
<input type="checkbox" name="checkb" id="Customer" value="Customer"> type=Customer
<br />
<input type="checkbox" name="checkb" id="Phone" value="Phone"> type=Phone
<br />
<input type="checkbox" name="checkb" id="ID_Card" value="ID_Card"> type=ID_Card
<br />
<input type=datetime id="Start_Date" value="" placeholder="Start_Date" />
<input type=datetime id="End_Date" value="" placeholder="End_Date" />
<button id="date">
Interval
</button>
On clicking of the Interval button if any checkboxes are checked they should get unchecked.
Below is the event listener for the Interval button:
var check1 = document.getElementById("Agent");
var check2 = document.getElementById("Customer");
var check3 = document.getElementById("Phone");
var check4 = document.getElementById("ID_Card");
var newBtn = document.getElementById("date");
if (newBtn) {
newBtn.addEventListener("click", function() {
if (check1.checked) {
var ischecked1 = check1.checked;
check1.checked != ischecked1;
}
if (check2.checked) {
var ischecked2 = check2.checked;
check2.checked != ischecked2;
}
if (check3.checked) {
var ischecked3 = check3.checked;
check3.checked != ischecked3;
}
if (check4.checked) {
var ischecked4 = check4.checked;
check4.checked != ischecked4;
}
});
}
Below code runs without any errors, but the boxes do not get unchecked if they are checked.
Below is the fiddle
Your statements are just evaluating as booleans, not performing assignments:
check1.checked != ischecked1; // this returns a boolean, doesn't do any assignment
You want to do this to toggle the checked state:
check1.checked = !ischecked1;
Same thing for other checkboxes.
There's also no need to create the extra variables, you can just do the toggling and reading directly:
check1.checked = !check1.checked;
Since you're only toggling checkboxes when they are checked, you can just directly set them to false as well.
if (check1.checked) check1.checked = false;
Instead of having if statements, you can use array iteration to do the toggling:
[check1, check2, check3, check4].forEach(check => {
if (check.checked) {
check.checked = false;
}
});
// or query the checkboxes directly and do the same
[...document.querySelectorAll('input[type="checkbox"]')].forEach(check => {
if (check.checked) {
check.checked = false;
}
});
Your mistake is in this line:
check1.checked != ischecked1;
This actually means "compare if check1.checked is not equal to ischecked1".
Most simple solution would be to remove the if statement and just do this:
check1.checked = !check1.checked
This means "set check1.checked to the opposite of check1.checked".
Since all checkboxes have the same name you could also collect all checkboxes by requesting them by name and use a loop to walk through them. A small example:
// Collect all checkboxes with a CSS selector that matches all input
// elements with a name attribute that's equal to "checkb"
var checkboxes = document.querySelectorAll('input[name="checkb"]');
var newBtn = document.getElementById("date");
if (newBtn) {
newBtn.addEventListener("click", function() {
// this is a for loop, it will run for as long as i
// is smaller than the amount of found checkboxes (checkboxes.length)
for(var i = 0; i < checkboxes.length; i++) {
// Get the checkbox from the checkboxes collection
// collection[i] means get item from collection with index i
var checkbox = checkboxes[i];
// Revert the .checked property of the checkbox
checkbox.checked = !checkbox.checked;
}
});
}
By the looks of it you just want to uncheck everything on click of button
you can just do this
var newBtn = document.getElementById("date");
if (newBtn) {
newBtn.addEventListener("click", function() {
document.getElementById("Agent").checked =
document.getElementById("Customer").checked =
document.getElementById("Phone").checked =
document.getElementById("ID_Card").checked = false;
});
}
I have a form located on my html page with a bunch of checkboxes as options. One of the options is "check-all" and I want all the other check boxes to be checked, if unchecked, as soon as the "check-all" box is checked. My code looks something like this:
<form method = "post" class = "notification-options">
<input type = "checkbox" name = "notification-option" id = "all-post" onClick = "javascript:checkALL(this
);"> All Posts <br/>
<input type = "checkbox" name = "notification-option" id = "others-post"> Other's Posts <br/>
<input type = "checkbox" name = "notification-option" id = "client-post"> Cilent's Post <br/>
<input type = "checkbox" name = "notification-option" id = "assign-post"> Task Assigned </form>
java script:
<script type = "text/javascript">
var $check-all = document.getElementbyId("all-post");
function checkALL($check-all){
if ($check-all.checked == true){
document.getElementByName("notification-option").checked = true;
}
}
</script>
nothing happens when I run my code
Here are some guidelines.
type attribute is not needed and can be omitted.
JS variable names can't contain hyphens, a typo in
getElementById()
You're using a global variable name as an argument, in the same time
you're passing this from online handler. The passed argument shadows the
global within the function.
if (checkAll.checked) does the job
Typo in getElementsByName(), gEBN() returns an HTMLCollection,
which is an array-like object. You've to iterate through the
collection, and set checked to every element separately.
Fixed code:
<script>
var checkAll = document.getElementById("all-post");
function checkALL(){
var n, checkboxes;
if (checkAll.checked){
checkboxes = document.getElementsByName("notification-option");
for (n = 0; n < checkboxes.length; n++) {
checkboxes[n].checked = true;
}
}
}
</script>
You can also omit the javascript: pseudo-protocol and the argument from online handler.
You can do it like this using jQuery:
$("#all-post").change(function(){
$('input:checkbox').not(this).prop('checked', this.checked);
});
Here is a JSfiddle
if all post check box is checked it will set check=true of others-post and client-post check boxes
$("input[id$=all-post]").click(function (e) {
if ($("input[id$=all-post]").is(':checked')) {
$("input[id$=others-post]").prop('checked', true);
$("input[id$=client-post]").prop('checked', true);
}
});
Check to see if any of the checkboxes are not checked first.
If so, then loop through them and check any that aren't.
Else, loop through them and uncheck any that are checked
I have an example at http://jsbin.com/witotibe/1/edit?html,output
http://jsfiddle.net/AX3Uj/
<form method="post" id="notification-options">
<input type="checkbox" name="notification-option" id="all-post"> All Posts<br>
<input type="checkbox" name="notification-option" id="others-post"> Other's Posts<br>
<input type="checkbox" name="notification-option" id="client-post"> Cilent's Post<br>
<input type="checkbox" name="notification-option" id="assign-post"> Task Assigned
</form>
function checkAll(ev) {
checkboxes = document.getElementById('notification-options').querySelectorAll("input[type='checkbox']");
if (ev.target.checked === true) {
for (var i = 0; i < checkboxes.length; ++i) {
checkboxes[i].checked = true;
}
} else {
for (var i = 0; i < checkboxes.length; ++i) {
checkboxes[i].checked = false;
}
}
}
I have a group of 4 checkboxes.
When any two have been checked they have their values copied to two hidden input fields.
The first checked checkbox value goes to the first input id="checkedBox1"
How do I get the second checked checkbox value to go to the second hidden input field id="checkedBox2"
I have used the JavaScript function below to place the values into each input from the individual checkboxes but can't figure out how to iterate through the list of all four checkboxes and place the two checked ones into each separate input field.
Checkboxes:
<input type="checkbox" value="test1" id="a" name="one"><label>Test11</label>
<input type="checkbox" value="test2" id="b" name="one"><label>Test12</label>
<input type="checkbox" value="test3" id="c" name="one"><label>Test13</label>
<input type="checkbox" value="test4" id="d" name="one"><label>Test14</label>
<input type="hidden" value="" id="checkedBox1">
<input type="hidden" value="" id="checkedBox2">
<script>
function populate() {
var checkboxes = document.getElementsByName('one');
var ip1 = document.getElementById('checkedBox1');
var ip2 = document.getElementById('checkedBox2');
// clear current values
ip1.value = ip2.value = '';
var first = false;
var second = false;
// Loop over checkboxes,stop when found 2 that are checked
for (var i=0,iLen=checkboxes.length; i<iLen || !(first && second); i++) {
if (checkboxes[i].checked) {
if (!first) {
ip1.value = checkboxes[i].value;
first = true;
} else if (!second) {
ip2.value = checkboxes[i].value;
second = true;
}
}
}
}
$('input[type="checkbox"]').on('change', function() {
populate();
}).change();
</script>
You could try plain JS, though I would use form property access rather than getElementsByName or getElementById:
function populate() {
var checkboxes = document.getElementsByName('one');
var ip1 = document.getElementById('checkedBox1');
var ip2 = document.getElementById('checkedBox2');
// clear current values
ip1.value = ip2.value = '';
var first = false;
var second = false;
// Loop over checkboxes,stop when found 2 that are checked
for (var i=0,iLen=checkboxes.length; i<iLen || !(first && second); i++) {
if (checkboxes[i].checked) {
if (!first) {
ip1.value = checkboxes[i].value;
first = true;
} else if (!second) {
ip2.value = checkboxes[i].value;
second = true;
}
}
}
}
Edit
Thanks Mal, added a line to clear the values of the hidden inputs each time.