Code returns all the items in Checkboxes - javascript

In here i want to get allRefItems but it should be checked & NOT disabled.But in here always get
all the Id's
var allRefItems = [];
$('table#reftable > tbody > tr').each(function () {
if ($(this).find('td:eq(0) input', this).is(':checked')) {
if ($(this).find('td:eq(0) input', this).not(':disabled')) {
itId = $(this).find('td:eq(0) input', this).attr('id');
allRefItems.push(itId);
}
}
});

If you want to get all checkboxes in table i think you could do it easier:
var allRefItems = [];
$('table#reftable > tbody input[type="checkbox"]') //get all checboxes
.filter(function() { // filter them only checked and not disabled
return !this.disabled && this.checked;
}).each(function () { //getting your ids
itId = $(this).attr('id');
allRefItems.push(itId);
});
Here is an jsFiddle example.

You can use,
var allRefItems = $('table#reftable > tbody > tr input[type="checkbox"]:checked:not(:disabled)').map(function() {
return this.id;
}).get();

Related

Using same JS function for multiple HTML tables?

I have function which adds and delete rows of a table on click of a button i.e add_row. Now i have multiple tables and for which i want to use the same function on the same page.
So below function is for table1, how do i reuse the same function for table2,table3 .. etc? Each table will have its own add_row button i.e, add_row,add_row1, add_row2 etc..
<script type="text/javascript">
$(document).ready(function() {
var rowIdx = 0;
$('#add_row').on('click', function () {
$.each($("#table1 tr"), function() {
if (parseInt($(this).data("id")) > rowIdx) {
rowIdx = parseInt($(this).data("id"));
console.log(rowIdx)
}
});
rowIdx++;
$('#table1').append(`<tr id="addr${rowIdx}" data-id="${rowIdx}" class="hidden">
<td data-name="id">
<input type="text" name='id${rowIdx}' placeholder='ID' value=""`);
});
$('#table1').on('click', '.remove', function () {
var child = $(this).closest('tr').nextAll();
child.each(function () {
var id = $(this).attr('id');
var idx = $(this).children('.row-index').children('p');
var dig = parseInt(id.substring(4));
idx.html(`Row ${dig - 1}`);
$(this).attr('id', `addr${dig - 1}`);
});
$(this).closest('tr').remove();
rowIdx--;
}
);
});
</script>
You mean this?
Don't add and subtract from rowIndex. It is different per table. Use the actual number of rows in the specific table
$(function() {
$('.add_row').on('click', function() {
const $table = $(this).closest("table");
const $rows = $table.find("tr");
let rowIndex = $rows.length;
$table.append(`<tr id="addr${rowIdx}" data-id="${rowIdx}" class="hidden">
<td data-name="id"><input type="text" name='id${rowIdx}' placeholder='ID' value=""</td></tr>`);
});
$(document).on('click', '.remove', function() {
var child = $(this).closest('tr').nextAll();
child.each(function() {
var id = $(this).attr('id');
var idx = $(this).children('.row-index').children('p');
var dig = parseInt(id.substring(4));
idx.html(`Row ${dig - 1}`);
$(this).attr('id', `addr${dig - 1}`);
});
$(this).closest('tr').remove();
});
});

I have a search and checkbox filter that should be filtering together, but my checkbox filter code isn't working

For some reason, my checkbox filter isn't working but my search filter is. What's wrong with it? Here is my search + checkbox filter below:
// search filter (working)
$(document).ready(function() {
$("#myInput").keyup(function() {
// Retrieve the input field text and reset the count to zero
var filter = $(this).val(),
count = 0;
// Loop through the comment list
$("tr").each(function() {
// If the list item does not contain the text phrase fade it out
if ($(this).text().search(new RegExp(filter, "i")) < 0) {
$(this).fadeOut(0).addClass('hidden');
// Show the list item if the phrase matches and increase the count by 1
} else {
$(this).show().removeClass('hidden');
count++;
}
});
// Update the count
var numberItems = count;
$("#filter-count").text("Number of Rows = " + count);
});
});
// checkbox filter (not working)
$(document).ready(function() {
$('#myTable tr' + $(this).attr('rel')).show();
$('div.modal-body').find('input:checkbox').live('click', function() {
if ($('div.modal-body').find('input:checkbox:checked').length > 0) {
$('#myTable tr').hide();
$('div.modal-body').find('input:checked').each(function() {
$('#myTable tr' + $(this).attr('rel')).not('.hidden').show();
});
} else {
$('#myTable tr').not('.hidden').show();
}
});
});
live is depreciated in latest versions of jquery, use on instead for your event.
$(document).ready(function () {
$('#myTable tr' + $(this).attr('rel')).show();
$('div.modal-body').find('input:checkbox').on('change', function () {
if($('div.modal-body').find('input:checkbox:checked').length > 0){
$('#myTable tr').hide();
$('div.modal-body').find('input:checked').each(function () {
$('#myTable tr' + $(this).attr('rel')).not('.hidden').show();
});
} else {
$('#myTable tr').not('.hidden').show();
}
});
});

Find value in all TD with Highlighting

I have this script for searching in table with Highlighting value from "input". But only for first TD in all TR.
Function remove Highlighting
function removeHighlighting(highlightedElements){
highlightedElements.each(function(){
var element = $(this);
element.replaceWith(element.html());
})
}
Function add Highlighting
function addHighlighting(element, textToHighlight){
var text = element.text();
var highlightedText = '<em>' + textToHighlight + '</em>';
var newText = text.replace(textToHighlight, highlightedText);
element.html(newText);
}
Searching in table but only in first TD in TR
$("#search").on("keyup", function() {
var value = $(this).val();
removeHighlighting($("table tr em"));
$("table tr").each(function(index) {
if (index !== 0) {
$row = $(this);
var $tdElement = $row.find('td:first');
var id = $tdElement.text();
var matchedIndex = id.indexOf(value);
if (matchedIndex != 0) {
$row.hide();
}
else {
addHighlighting($tdElement, value);
$row.show();
}
}
});
});
I don´t know how can I searching in all TD and How can I write e.g. some alert if "matchedIndex == -1" (if not found some value from input)
Try looping in all TDs of TR
$("table tr").each(function(index) {
if (index !== 0) {
row = $(this);
$("td", this).each(function(idx) {
var id = $(this).text(); //or $(this).innerText
var matchedIndex = id.indexOf(value);
if (matchedIndex != 0) {
$row.hide();
}
else {
addHighlighting($tdElement, value);
$row.show();
}
}
}
});
A short way
$("table tr > td em").each(function(){
$( this ).replaceWith( $( this ).text() );
});
Adding a span tag with a highlight class is the way to go like suggested in the comments.
Please find a working demo below and in this jsFiddle.
There is a really useful function to remove all the wrapping of the spans. You can do this with $('span.highlight').contents().unwrap().
For finding the text you can use string.search(searchText) or string.match(searchText). The search method will return -1 if nothing is found and the position of the text if found. And match would return occurences in the searchText.
For testing that it finds the first occurence I have added TestY in the table. The flag matched is responsible for this behavior. If you would remove it, it would highlight both TestY elements.
(function () {
var removeHighlight = function () {
$('span.highlight').contents().unwrap();
};
var wrapContent = function (index, $el, text) {
var $highlight = $('<span class="highlight"/>')
.text(text.substring(0, index));
//console.log(text.substring(0, index));
var normalText = document.createTextNode(text.substring(index, text.length));
//console.log(index, $highlight.text(), normalText);
$el.html($highlight).append(normalText);
};
var highlightTextInTable = function ($tableElements, searchText) {
// highlights if text found (during typing)
var matched = false;
//remove spans
removeHighlight();
$.each($tableElements, function (index, item) {
var $el = $(item);
if ($el.text().search(searchText) != -1 && !matched) {
//console.log("matched", $el, $el.html());
wrapContent(searchText.length, $el, $el.html());
//console.log(searchText, $el.text());
if (searchText == $el.text()) {
// found the entry
//console.log("matched");
matched = true;
}
}
});
};
$(function () {
//load table into object
var $tableRows = $('table tr');
var $tableElements = $tableRows.children();
//console.log($tableRows, $tableElements);
$('#search').on('keyup', function (e) {
var searchText = $(this).val();
if (searchText.length == 0) {
// catches false triggers with empty input (e.g. backspace delete or case lock switch would trigger the function)
removeHighlight(); // remove last remaining highlight
return;
}
highlightTextInTable($tableElements, searchText);
});
});
})();
.highlight {
background-color: #00FFFF;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="search" />
<table>
<tr>
<td>TestX</td>
<td>Test1.2</td>
<td>Test1.3</td>
<td>Test1.4</td>
</tr>
<tr>
<td>Test2.1</td>
<td>TestY</td>
<td>Test2.3</td>
<td>Test2.4</td>
</tr>
<tr>
<td>Test3.1</td>
<td>TestY</td>
<td>Test3.3</td>
<td>Test3.4</td>
</tr>
</table>

$(this) issue when defining a function

I have this code to remove table rows on select. (Fiddle)
$('select').change(function() {
var $this = $(this),
list = $('table tbody tr'),
findoption = $this.find('option:selected'),
selected = findoption.data('hide'),
show_hide_li = $this.find("."+selected);
if (selected == "reset") {
list.show();
}
else {
$('.'+selected).show();
list.not('.'+selected).hide()
}
});
When I move the code out of the change function and define it like the following, I have an issue with the $(this) that prevents the code from working. Can anyone tell me how to define a function when there is $(this) in the code?
var cancel = function(){
var $this = $(this),
list = $('table tbody tr'),
findoption = $this.find('option:selected'),
selected = findoption.data('hide'),
show_hide_li = $this.find("."+selected);
if (selected == "reset") {
list.show();
}
else {
$('.'+selected).show();
list.not('.'+selected).hide()
}
}
$('select').change(function() {
cancel();
});
I think this is what you're trying to do.
function cancel(){
var $this = $(this),
list = $('table tbody tr'),
findoption = $this.find('option:selected'),
selected = findoption.data('hide'),
show_hide_li = $this.find("."+selected);
if (selected == "reset") {
list.show();
}
else {
$('.'+selected).show();
list.not('.'+selected).hide()
}
}
$('select').change(cancel);
You can pass the "this" as a parameter to the function
var cancel = function(param1){
var $this = $(param1),
list = $('table tbody tr'),
findoption = $this.find('option:selected'),
selected = findoption.data('hide'),
show_hide_li = $this.find("."+selected);
if (selected == "reset") {
list.show();
}
else {
$('.'+selected).show();
list.not('.'+selected).hide()
}
}
$('select').change(function() {
cancel(this);
});
Use .on method of jquery
$('select').on('change', cancel);
var cancel = function(){
var $this = $(this),
list = $('table tbody tr'),
findoption = $this.find('option:selected'),
selected = findoption.data('hide'),
show_hide_li = $this.find("."+selected);
if (selected == "reset") {
list.show();
}
else {
$('.'+selected).show();
list.not('.'+selected).hide()
}
}
This very brief, but powerful line, should replace the ones shown after:
$('select').change(cancel);
Replace below lines with above one:
$('select').change(function() {
cancel();
});
Because these three lines are equivalent to:
$('select').change(function() {
//you have access to 'this' here
function() {
//your body
}
});
And as you can see the inner function has no access to this unless you explicitly pass it as a parameter, which your can easily avoid by removing nested functions.

jquery remove duplicate li

<ul id="myid">
<li>microsoft</li>
<li>microsoft</li>
<li>apple</li>
<li>apple</li>
</ul>
I want to remove duplicates from li by using jquery.
How can I do that?
example
I find that the script is faster
var liText = '', liList = $('#myid li'), listForRemove = [];
$(liList).each(function () {
var text = $(this).text();
if (liText.indexOf('|'+ text + '|') == -1)
liText += '|'+ text + '|';
else
listForRemove.push($(this));
})​;
$(listForRemove).each(function () { $(this).remove(); });
uniqueLi = {};
$("#myid li").each(function () {
var thisVal = $(this).text();
if ( !(thisVal in uniqueLi) ) {
uniqueLi[thisVal] = "";
} else {
$(this).remove();
}
})
This build an index (an object) of unique values. For your example, uniqueLi will look like this afterwards:
{
"microsoft": "",
"apple": ""
}
So whenever a value is encountered that has been added to the index before, the associated <li> gets removed.
You could use
var inner = [];
$('li').each( function(index, Element){
if (jQuery.inArray(this.innerHTML, inner) == -1){
inner.push(this.innerHTML);
}
else {
$(this).remove();
}
});
Here's a function that will do it, a slightly different way:
function removeDuplicateItems(id) {
var ul = $('#' + id);
$('li', ul).each(function() {
if($('li:contains("' + $(this).text() + '")', ul).length > 1)
$(this).remove();
});
}
Call with removeDuplicateItems('myid');
I have used #Thariama solution in the past, but I have compatibility problems with IE6 (I still needs to support this dinosaur).
If the item repeats, so remove it from ul. It works with dynamic added li.
var seen = {};
$("ul#emails_exclusion_list").find("li").each(function(index, html_obj) {
txt = $(this).text().toLowerCase();
if(seen[txt]) {
$(this).remove();
} else {
seen[txt] = true;
}
});

Categories