Checkbox checked only based selected in array of ids - javascript

when I checked the first page 2 checkboxes and 2nd page I checked 1 checkbox both are stored in a selected_Ids = [] and when switched again first page should appear check box checked for example:
HTML
<input type="checkbox" class="selectable_candidate" id="candidate_#{candidate.id}" data-candidate-id= "#{candidate.id}">
JS
var selected_Ids = [];
$('body').on('click', '.selectable_candidate', function() {
var self = $(this);
if (self.is(':checked')) {
selected_Ids.push(self.attr("id"));
}else{
const index = selected_Ids.indexOf($(this).attr("id"));
if (index > -1) {
selected_Ids.splice(index, 1);
}
}
console.log(selected_Ids);
});
selected_Ids -> ['candidate_17', 'candidate_18', 'candidate_19']
please help to write code for this.

Related

Unchecking of the checked checkboxes on another button click

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;
});
}

check two input element's names are different or not using javascript

I have an array in which the values of check boxes gets stored on user click. Now I need to use an if loop for a particular logic in my code to give a condition whether the elements inside the array have same name (group check box name) or different names. How can I do it in javascript or jquery?
var Array = ['bob','bob','smith','smith','john','john'];
var UniqueArray = new Array();
var obj = {};
$.each(Array , function(i,value) {
if(!obj[value]) {
obj[value] = true;
UniqueArray.push(value)
}
})
Are you expecting something like this.
$(function() {
// create an array.
var elements = [];
// click event for all input of type checkbox.
$('[type="checkbox"]').on("click", function() {
// restrict no. of items to be inserted into the array to 2
if (elements.length <= 2) {
// push each element to array.
elements.push($(this));
}
// compare name attribute of 1st and 2nd element in array.
if (elements.length == 2) {
if (elements[0].attr('name') == elements[1].attr('name')) {
alert('elements with same name');
} else {
alert('elements with differnt name');
}
//clear all elements from array.
elements = [];
//clear all checkbox.
$('input:checkbox').removeAttr('checked');
}
// if you want to iterate through array use $.each
/*$.each(elements,function(index,data){
alert(data.attr('name'));
});
*/
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
first checkbox - :"myCheckBox":
<input type="checkbox" name=myCheckBox id="cbxCustom1" />
<br>second checkbox - :"myCheckBox":
<input type="checkbox" name=myCheckBox id="cbxCustom2" />
<br>third checkbox - :"myCheckBoxNew":
<input type="checkbox" name=myCheckBoxNew id="cbxCustom3" />

how to get all checkboxes from one of three forms?

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?

How to unfilter table rows when checkbox is unchecked

I have a jquery script that filters rows with a looping function when a check box is checked, or words are typed in a text box. The textbox works perfectly when you erase the words it will unfilter, however the check boxes when you uncheck them it doesn't unfilter. It will switch between the two check boxes for on and off.
However, you can trick it to unfilter the checkboxes applied filter by filtering by name and typing in the textbox and then erasing what you typed.
Thus,
I don't know why when you uncheck a check box it doesn't unfilter it because how could it keep applying the filter every-time it loops if the box is not checked.
var $rows = $("#data tr"),
$filter = $("#filter");
$("#filter").keyup(function () {
var filterText = $filter.val().toLowerCase();
$rows.each(function () {
var $row = $(this);
$row.toggle($row.text().toLowerCase().indexOf(filterText) > -1);
});
});
var $row_on = $("#data tr"),
$filter_poweron = $("#poweron");
if(($filter_poweron).is(':checked')) {
var filterText_poweron = $filter_poweron.val().toLowerCase();
$row_on.each(function () {
var $row_d = $(this);
$row_d.toggle($row_d.text().toLowerCase().indexOf(filterText_poweron) > -1);
});
}
var $row_off = $("#data tr"),
$filter_poweroff = $("#poweroff");
if(($filter_poweroff).is(':checked')) {
var filterText_poweroff = $filter_poweroff.val().toLowerCase();
$row_off.each(function () {
var $row_do = $(this);
$row_do.toggle($row_do.text().toLowerCase().indexOf(filterText_poweroff) > -1);
});
}
<td width='200' align='left'>
<br><br>Filter: <input type='text' name='' id='filter' value='' style='width:270px;' data-toggle="tooltip" data-placement="left" title="Filter VM List." placeholder='Type to filter'>
<br><input type="checkbox" id="poweron" value="1O">PoweredOn <input type="checkbox" id='poweroff' value="0F"> PoweredOff
</td>
You probably want to move the if(($filter_poweron).is(':checked')) {...} stuff inside an event listener so that it runs every time the checkbox is clicked or changed.
Something like:
var $rows = $("#data tr");
$("#filter").keyup(function() {
var filterText = $(this).val().toLowerCase();
$rows.each(function() {
var $row = $(this);
$row.toggle($row.text().toLowerCase().indexOf(filterText) > -1);
});
});
$("#poweron, #poweroff").on('click change', function() {
var filterText = $(this).val().toLowerCase();
var isChecked = $(this).is(':checked');
$rows.each(function() {
var $row_do = $(this);
var showRow = isChecked ? $row_do.text().toLowerCase().indexOf(filterText) > -1 : true;
$row_do.toggle(showRow);
});
});
A couple side notes:
var $rows = $("#data tr") and var $row_on = $("#data tr") and var $row_off = $("#data tr") are all redundant (querying the dom 3 times with the same query). You just need one variable for $rows. Also, you don't need parens around ($filter_poweron).is().

jQuery help with checking parent of checked child checkbox

I have a main row and some other rows underneath that main row like this:
[checkbox] Main heading row
[checkbox] first child row
[checkbox] second child row
When I click on the child row, it should check the parent (main) row automatically. Problem is that it doesn't check it first time I click it. I have to check the first child row first, then uncheck the first child row and then check first child row again to get the parent (main) row get checked. I want the parent row get checked as soon as any of the child rows get checked.
I am using the following code
function checkbox_click(){
var n = event.srcElement;
if(n.parentElement.id == "row"){
n = n.parentElement;
}
if(n.id == "row"){
alert("ID: 1");
n.rs = n.parentElement;
if(this.multiSelect == 0){ // single select
alert("ID: 2");
n.all[0].checked = 1;
this.selectedRows = [ n ];
if(this.lastClicked && this.lastClicked != n){
this.lastClicked.all[0].checked = 0;
this.lastClicked.style.color = "000099";
this.lastClicked.style.backgroundColor = "";
}
} else {
alert("ID: 3");
n.all[0].click();
}
if(this.parentElement == pg.procs) {
alert("ID: 4");
var terminate = false;
var counter = 0;
if(n.className == "proc") {
alert("ID: 5");
z = n.nextSibling;
while(z.id == "row" && z.className != "proc" && !terminate) {
alert("ID: 6");
z.all[0].checked = 0;
z.style.backgroundColor = z.className == "w" ? "ffffff" : "ffffcc";
counter++;
if(counter > 1000) terminate = true;
z = z.nextSibling;
}
} else {
$(".row input").change(function() {
alert("ID: 7");
var $row= $(this).closest(".row");
var $main_row = $row.prev('.proc').length ? $row.prev('.proc') : $row.prevUntil(".proc").prev();
$main_row.find(":checkbox").attr("checked", function(i,attr) {
return $main_row.nextUntil('.proc').filter(':has(input:checked)').length ? "checked" : false;
});
});
$(".proc input").change(function() {
alert("ID: 8");
$(this).closest(".proc").nextUntil('.proc').children(':checkbox').attr('checked', this.checked);
});
}
If you want to check the parent checkbox when one of the child checkboxes is checked, I would suggest using a common class for the child checkboxes, and a unique id attribute for the parent checkbox (or store it as a variable).
Let's assume you have a structured HTML document that contains something like the following:
<div>
<input type="checkbox" name="ckparent" id="ckparent" />
<label for="ckparent">Parent</label>
<div>
<input type="checkbox" name="ckchild1" id="ckchild1" class="ckchild" />
<label for="ckchild1">Child 1</label>
</div>
<div>
<input type="checkbox" name="ckchild2" id="ckchild2" class="ckchild" />
<label for="ckchild2">Child 2</label>
</div>
</div>
You could then write the following jQuery code to check the parent checkbox when either of the children are checked:
$('input:checkbox.ckchild').click(function(event) {
var checked = $(this).is(':checked');
if (checked) {
$('#ckparent').attr('checked', true);
}
});
EDIT: The order in which the changed and clicked events are fired with regards to when the checked attribute is actually changed is dependent on the browser you are using -- which browsers are you targeting?

Categories