Create Simple J Query todo list - javascript

I am trying to create a simple todo list in Javascript but for some reason when the check box is ticked, the styling text adjacent to it does not change rather the heading text style changes as per the fiddle
HTML:
<table border="1">
<tr>
<td>
<input type="checkbox" value="None" id="squaredTwo" name="check" />
</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>
<input type="checkbox" value="None" id="squaredTwo" name="check" />
</td>
<td>row 2, cell 2</td>
</tr>
</table>
<h2> Heading 2</h2>
CSS:
.newclass {
text-decoration: line-through;
color: red;
}
JQuery:
$('input[type="checkbox"]').click(function () {
if ( this.checked ) {
//alert('Checked');
$("h2").addClass('newclass');
} else {
//alert('Unchecked');
$("h2").removeClass('newclass');
}
});
Please help

Change your Jquery like this
$('input[type="checkbox"]').click(function () {
if (this.checked) {
//alert('Checked');
$(this).closest("td").next().addClass('newclass');
} else {
//alert('Unchecked');
$(this).closest("td").next().removeClass('newclass');
}
});
Demo Fiddle
Even Simpler than that
$('input[type="checkbox"]').click(function () {
$(this).closest("td").next().toggleClass('newclass');
});
New Demo Fiddle

It is happening as you are targeting H2 element for styles on click of checkbox. Instead use the next TD element.
$('input[type="checkbox"]').click(function() {
if (this.checked) {
//alert('Checked');
$(this).parent().next().addClass('newclass');
} else {
//alert('Unchecked');
$(this).parent().next().removeClass('newclass');
}
});

Related

how to highlight row on mouse click?

I have a table with rows of data. I am able to highlight the table when the checkbox is checked. I would like to enable the highlight and enable the checkbox on a mouse click over the table. the problem with my code now is that when I click on the check box its triggers the event for the mouse click to as the check box is part of the <tr> how can I fix this.
$('.form-check-input').on('click', function() {
if ($(this).is(':checked')) {
$(this).closest("tr").addClass("rowColor");
} else {
$(this).closest("tr").removeClass("rowColor");
}
});
$('#table1 tbody tr').on('click', function() {
//$(this).find(".form-check-input").checked = true;
var checkBox = $(this).find(".form-check-input");
if (checkBox.is(':checked')) {
checkBox.attr("checked", false);
$(this).removeClass("rowColor");
} else {
checkBox.attr("checked", true);
$(this).addClass("rowColor");
}
});
.rowColor {
background-color: #dfecf6;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table1" class="table table-striped">
//thead
<tbody>
<tr class="">
<td></td>
<td class="checkboxtd"><input class="form-check-input" type="checkbox" value="" id=""></td>
</tr>
</tbody>
<table>
Issue with above code is when checkbox clicked it also trigger parent element click event. you can stop that by calling stopPropagation() for event. here is updated code
$('.form-check-input').on('click', function(e) {
e.stopPropagation();
if ($(this).is(':checked')) {
$(this).closest("tr").addClass("rowColor");
} else {
$(this).closest("tr").removeClass("rowColor");
}
});
$('#table1 tbody tr').on('click', function() {
$('.form-check-input').trigger("click");
return;
});
.rowColor {
background-color: #dfecf6;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table1" class="table table-striped">
//thead
<tbody>
<tr class="">
<td>test</td>
<td class="checkboxtd"><input class="form-check-input" type="checkbox" value="" id=""></td>
</tr>
</tbody>
<table>
You had two events overlap each other because the checkbox click was bubbling to the tr click. I added e.stopPropagation(); to keep it from happening.
$('.form-check-input').on('click', function(e) {
e.stopPropagation();
if ($(this).is(':checked')) {
$(this).closest("tr").addClass("rowColor");
} else {
$(this).closest("tr").removeClass("rowColor");
}
});
$('#table1 tbody tr').on('click', function() {
//$(this).find(".form-check-input").checked = true;
var checkBox = $(this).find(".form-check-input");
if (checkBox.is(':checked')) {
checkBox.attr("checked", false);
$(this).removeClass("rowColor");
} else {
checkBox.attr("checked", true);
$(this).addClass("rowColor");
}
});
table {
width: 100%
}
.rowColor {
background-color: #dfecf6;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table1" class="table table-striped">
//thead
<tbody>
<tr>
<td>&nbsp</td>
<td class="checkboxtd">
<input class="form-check-input" type="checkbox" value="" id="">
</td>
</tr>
</tbody>
</table>
First of all some other this about your code:
you should use checkBox.prop("checked", false); and not .attr to set the current state of the checkbox.
you normally want to listen to the change (or input) event on an input element if you want to get notified about a change a click. A checkbox could also be checked/unchecked by using other input devices like a keyboard.
To your problem, there are different ways of targeting the problem.
My first and highly suggested solution would be to rewrite the logic of your code: I would go with only changing the checked state of the checkbox in the tr event handler and then trigger the change event on the checkbox.
$('.form-check-input').on('change', function(e) {
if ($(this).is(':checked')) {
$(this).closest("tr").addClass("rowColor");
} else {
$(this).closest("tr").removeClass("rowColor");
}
});
$('#table1 tbody tr').on('click', function(e) {
var checkBox = $(this).find(".form-check-input");
if (!$(e.target).is(checkBox)) {
// toggle the check state
checkBox.prop("checked", !checkBox.is(':checked'));
// trigger the change event
checkBox.trigger("change")
}
});
.rowColor {
background-color: #dfecf6;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table1" class="table table-striped">
//thead
<tbody>
<tr class="">
<td></td>
<td class="checkboxtd"><input class="form-check-input" type="checkbox" value="" id=""></td>
</tr>
</tbody>
<table>
If you really want to keep your code that way - which I won't suggest due to the above-mentioned reason - you could go with the way to prevent the propagation of the event in the click event handler of the input element, that way it won't reach the tr element.
$('.form-check-input').on('click', function(e) {
e.stopPropagation()
if ($(this).is(':checked')) {
$(this).closest("tr").addClass("rowColor");
} else {
$(this).closest("tr").removeClass("rowColor");
}
});
$('#table1 tbody tr').on('click', function(e) {
//$(this).find(".form-check-input").checked = true;
var checkBox = $(this).find(".form-check-input");
if (checkBox.is(':checked')) {
checkBox.prop("checked", false);
$(this).removeClass("rowColor");
} else {
checkBox.prop("checked", true);
$(this).addClass("rowColor");
}
});
.rowColor {
background-color: #dfecf6;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table1" class="table table-striped">
//thead
<tbody>
<tr class="">
<td></td>
<td class="checkboxtd"><input class="form-check-input" type="checkbox" value="" id=""></td>
</tr>
</tbody>
<table>
The other way would be to check in the event handler of the tr element if the click event originated from the input element, using $(e.target).is(checkBox). That way you could also change your event listener to listen for change instead of click for the checkbox. But I wouldn't recommend that either.
$('.form-check-input').on('change', function(e) {
if ($(this).is(':checked')) {
$(this).closest("tr").addClass("rowColor");
} else {
$(this).closest("tr").removeClass("rowColor");
}
});
$('#table1 tbody tr').on('click', function(e) {
//$(this).find(".form-check-input").checked = true;
var checkBox = $(this).find(".form-check-input");
if (!$(e.target).is(checkBox)) {
if (checkBox.is(':checked')) {
checkBox.prop("checked", false);
$(this).removeClass("rowColor");
} else {
checkBox.prop("checked", true);
$(this).addClass("rowColor");
}
}
});
.rowColor {
background-color: #dfecf6;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table1" class="table table-striped">
//thead
<tbody>
<tr class="">
<td></td>
<td class="checkboxtd"><input class="form-check-input" type="checkbox" value="" id=""></td>
</tr>
</tbody>
<table>
I think you can do a few changes feel free to visit my solution in CodePen: https://codepen.io/juanmaescudero/pen/PojQKzm
Anyway I share you the code:
HTML:
<table id="table1" class="table table-striped">
<tbody>
<tr class="">
<td>highlight row</td>
<td class="checkboxtd"><input class="form-check-input" type="checkbox" value="" id=""></td>
</tr>
</tbody>
<table>
CSS:
.rowColor {
background-color: #dfecf6;
}
JS:
$(".form-check-input").on("click", (e) => {
e = e.target;
if ($(e).is(":checked")) {
$(e.closest("tr")).addClass("rowColor");
} else {
$(e.closest("tr")).removeClass("rowColor");
}
});
Regards 😁

If change element in DOM with JS not working event [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 2 years ago.
I have a function that changes a table in a list, so far so good, but when the function changes in js it stops working, if I reload the page it works but if I change the DOM nothing. Can you help me?
$(document).ready(function() {
$('#table-list tbody tr').click(function(event) {
if(event.target.type == 'checkbox'){
}else{
$(':checkbox', this).trigger('click');
}
});
$('#ul-list li').click(function(event) {
var checkbox_type = $(event.target).find("input[type='checkbox']").attr('name');
if(checkbox_type){
$(':checkbox', this).trigger('click');
}
});
});
These are the two events that should always be active. But if I change the table to ul not it works
So let me explain better, I have a table like this:
<table id="table-list">
<tbody>
<tr>
<td><input type="checkbox" name="1" /></td>
</tr>
<tr>
<td><input type="checkbox" name="3" /></td>
</tr>
</tbody>
</table>
Then by clicking on a button I convert it to a list by removing the table from the DOM and inserting this:
<ul id="ul-list">
<li>
<input type="checkbox" name="1" />
</li>
<li>
<input type="checkbox" name="3" />
</li>
</ul>
Now I want if I try to click on the list this function should start:
$('#ul-list li').click(function(event) {
var checkbox_type = $(event.target).find("input[type='checkbox']").attr('name');
if(checkbox_type){
$(':checkbox', this).trigger('click');
}
});
instead no.
If you rewrite the DOM, you need to DELEGATE
$('#ul-list').on("click","li",function(event) {
I though you might need this - see the stopPropagation when the target is one of the checkboxes itself:
function findCheck(e) {
const tgt = e.target;
if (tgt.type && tgt.type === "checkbox") {
e.stopPropagation()
} else {
const $row = $(e.currentTarget);
$row.find("[type=checkbox]").each(function() {
$(this).click();
//$(this).attr("checked", !$(this).attr("checked"))
});
}
}
$(function() {
let $ul = $("<ul/>", {
id: "ul-list"
});
const $tbl = $("#table-list");
$tbl.find("tr").each(function() {
let $li = $("<li/>")
$("td",this).each(function() {
$li.append($(this).html())
})
$ul.append($li);
})
$tbl.replaceWith($ul)
$('#ul-list').on("click", "li", findCheck)
})
tr {
background-color: red
}
li {
background-color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table-list">
<tbody>
<tr>
<td>1</td>
<td><input type="checkbox" name="1" /></td>
<td><input type="checkbox" name="2" /></td>
</tr>
<tr>
<td>2</td>
<td><input type="checkbox" name="3" /></td>
</tr>
</tbody>
</table>

Check/uncheck a checkbox in the table row when any checkbox in the same row is clicked

I have a simple table as following which has checkboxes in the first and last columns of each row.
<table style="width:100%">
<tr>
<td><input type="checkbox" /></td>
<td>Smith</td>
<td><input type="checkbox" /></td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>Jackson</td>
<td><input type="checkbox" /></td>
</tr>
</table>
Problem:
When I check/uncheck the last column's checkbox in the first row, the first column's checkbox in the same row should be checked/unchecked. Similarly, if I check/uncheck the first column's checkbox, the corresponding last column checkbox should be checked/unchecked.
How can I achieve this in javascript? Any help or pointers would be really appreciated.
Here is the fiddle which I have created: Fiddle
Thank you.
Use :checkbox selector to select input type checkbox elements.
Try this:
$(':checkbox').on('change', function() {
$(this).closest('tr').find(':checkbox').prop('checked', this.checked);
});
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table style="width:100%">
<tr>
<td>
<input type="checkbox" />
</td>
<td>Smith</td>
<td>
<input type="checkbox" />
</td>
</tr>
<tr>
<td>
<input type="checkbox" />
</td>
<td>Jackson</td>
<td>
<input type="checkbox" />
</td>
</tr>
</table>
Using JavaScript:
Use querySelectorAll('[type="checkbox"]') to find checkbox elements.
Try this:
var checkboxes = document.querySelectorAll('[type="checkbox"]');
[].forEach.call(checkboxes, function(checkbox) {
checkbox.onchange = function() {
var currentRow = this.parentNode.parentNode;
var cbElems = currentRow.querySelectorAll('[type="checkbox"]');
[].forEach.call(cbElems, function(cb) {
cb.checked = this.checked;
}.bind(this))
};
});
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
}
<table style="width:100%">
<tr>
<td>
<input type="checkbox" />
</td>
<td>Smith</td>
<td>
<input type="checkbox" />
</td>
</tr>
<tr>
<td>
<input type="checkbox" />
</td>
<td>Jackson</td>
<td>
<input type="checkbox" />
</td>
</tr>
</table>
One possible Javascript solution to toggle Checkboxes on Table Row click is shown below:
HTML
<table id = "Table1">
<tr>
<td><input type="checkbox" /></td>
<td>John Smith</td>
<td><input type="checkbox" /></td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>Anna Warner</td>
<td><input type="checkbox" /></td>
</tr>
</table>
CSS
table, th, td{
border: 1px solid #c0c0c0;
border-collapse: collapse;
}
table{width:100%;}
Javascript
// row click will toggle checkboxes
row_OnClick("Table1")
function row_OnClick(tblId) {
try {
var rows = document.getElementById(tblId).rows;
for (i = 0; i < rows.length; i++) {
var _row = rows[i];
_row.onclick = null;
_row.onclick = function () {
return function () {selectRow(this);};
}(_row);
}
}
catch (err) { }
}
function selectRow(row) {
row.cells[0].firstChild.checked = !row.cells[0].firstChild.checked;
row.cells[2].firstChild.checked = row.cells[0].firstChild.checked;
}
Working jsfiddle demo at: https://jsfiddle.net/t6nsxgnz/
Practical implementation at: http://busny.net
You can further customize this solution pertinent to your task by modifying the selectRow(row) function:
function selectRow(row) {
row.cells[0].firstChild.checked = // add your code for the 1st CheckBox
row.cells[2].firstChild.checked = // add your code for the 2nd CheckBox
}
Another variation of this functionality coded in jQuery can be found in online pop-quiz engine (http://webinfocentral.com), implemented via the follwoing code snippet:
// toggle Checkboxes on row click
$(Table1 tr').click(function (event) {
// find the checkbox in the row
var _chk = $(this).find('input:checkbox');
if (!($(event.target).is("checkbox"))) {
$(_chk).prop('checked', !$(_chk).prop('checked'));
}
});
In this case, Row Click (at any place of the Row) or CheckBox Click events will toggle the state of that particular CheckBox. The state of other CheckBoxes can be synchronized with this one (by using "siblings" property, for example).
Hope this may help.

Unmark checkbox when there is no more TR and TABLE goes hide

I'm working on this function for remove any marked checkbox in a selector container element. The code works fine but has a small problem: I'm not able to uncheck the first checkbox (the one that toggle all the checkboxes in a selector2 container). Now this is the code for remove the checked checkboxes:
function eliminarMarcados(selector, toggleMsg, msgSelector) {
$(selector + " input[type='checkbox']:checked").closest("tr").not('.tableHead').remove();
if (toggleMsg) {
if ($(selector + " tbody tr").length == 0) {
$(msgSelector).show();
$(selector).hide();
// 1st test didn't work since it's not right
//$(selector + " tr").hasClass('tableHead').$(selector + " input[type='checkbox']").prop('checked', false);
}
}
}
And this is how I call it:
$("#btnEliminarNorma").on('click', function () {
eliminarMarcados("#tablaNorma", true, "#alertSinNorma");
});
This is the code I'm using for toggle all checkboxes checked:
function marcarTodosCheck(selChk, tableBody) {
$(selChk).on('click', function () {
var $toggle = $(this).is(':checked');
$(tableBody).find("input:checkbox").prop("checked", $toggle).trigger("change");
});
$(tableBody).find("input:checkbox").on('click', function () {
if (!$(this).is(':checked')) {
$(selChk).prop("checked", false).trigger("change");
} else if ($(tableBody).find("input:checkbox").length == $(tableBody).find("input:checkbox:checked").length) {
$(selChk).prop("checked", true).trigger("change");
}
});
}
And I call it as follow:
marcarTodosCheck("#toggleCheckNorma", "#tablaNorma");
And this is the HTML code behind this:
<table class="table table-condensed" id="tablaNorma">
<thead>
<tr class="tableHead">
<th><input type="checkbox" id="toggleCheckNorma" name="toggleCheckNorma"></th>
<th>Nro.</th>
<th>Norma COVENIN</th>
<th>Año de Publicación</th>
<th>Comité Técnico</th>
</tr>
</thead>
<tbody id="normaBody">
<tr class="">
<td><input type="checkbox" value="5"></td>
<td>382</td><td>Sit alias sit.</td>
<td>1970</td><td>Velit eum.</td>
</tr>
<tr class="">
<td><input type="checkbox" value="6"></td>
<td>38362</td>
<td>Et voluptatem.</td><td>1976</td>
<td>Et voluptatem.</td>
</tr>
</tbody>
</table>
How I can unmark the first checkbox?
I've just made a Fiddle with an additional <button id="btnEliminarNorma">Uncheck</button> to remove the checkmarks and the adjustment of your first approach in the function eliminarMarcados() :
$(selector).find(" input[type='checkbox']").prop('checked', false);

Select data attribute from row only for rows with checked checkboxes

I have table has 2 columns: checkbox and name.
<table id="data">
<tr class="header">
<th>
<input type="checkbox" class="download" />
</th>
<th>Name</th>
</tr>
<tr data-id="1">
<td>
<input type="checkbox" class="download" />
</td>
<td>One</td>
</tr>
<tr data-id="2">
<td>
<input type="checkbox" class="download" />
</td>
<td>Two</td>
</tr>
<tr data-id="3">
<td>
<input type="checkbox" class="download" />
</td>
<td>Something</td>
</tr>
</table>
I would like to select data attribute from those rows that have checkbox selected. Right now I'm doing it this way:
$(document).on('click', "#select", function (e) {
var mydata=[];
$.each($('#data tbody tr:not(.header)'), function(i, row) {
if($(row).find('input[type=checkbox]').is(":checked"))
mydata.push($(row).data('id'));
});
console.log(mydata);
});
This works fine, but can this be done better/faster?
Here is my working demo: http://jsfiddle.net/Misiu/yytR2/2/
Also how can I uncheck checkbox in header when one of more checkboxes in body are unchecked and check it when all will get checked?
EDIT: My final working code (thanks to #tymeJV):
$(document).on('change', "#data tr.header input.download", function (e) {
$('#data tbody tr:not(.header) input.download').prop('checked', $(this).is(":checked"));
});
$(document).on('change', "#data tr:not(.header) input.download", function (e) {
if ($(this).is(":checked") && $('#data tr:not(.header) input.download:not(:checked)').length == 0) {
$('#data tbody tr.header input.download').prop('checked', true);
} else {
$('#data tbody tr.header input.download').prop('checked', false);
}
});
$(document).on('click', "#select", function (e) {
var rows = $("#data tr:not(.header) td input:checked").map(function () {
return $(this).closest("tr").data("id");
}).get();
console.log(rows);
});
You can do:
var rows = $("#data tr:not(.header) td input:checked").map(function() {
return $(this).closest("tr").data("id");
}).get();
It iterates yet, but only checked rows.
You can use:
$(".download:checkbox").map(function() {
return $(this).parents('tr').data('id');
}).get()

Categories