Jquery.each (): find elements containing input

I have a table with a section theadand tbody. I use jQuery to search and count everyone THin table. It works great. But at the same time I want to check whether TD THat tbodyany input elements.

Here is what I still have:

jQuery('#' + _target).each(function () {

        var $table = jQuery(this);
        var i = 0;
        jQuery('th', $table).each(function (column) {
            if (jQuery(this).find("input")) {
                dataTypes[i] = { "sSortDataType": "input" }
            }
            else {
                dataTypes[i] = { "sSortDataType": "html" }
            }

            i++;
        });
    });

I hope you have enough information to help me?

+3
source share
4 answers
dataTypes = $('#' + _target + ' th').map(function(i, th) {
  var $table = $(th).closest('table');
  var pos = $table.index(th) + 1;
  return { "sSortDataType": $table.find('td:nth-child('+pos+')').is(':has(input)') ? 'input' : 'html' };
});

Edit: if you use this in one table (in this case, the call eachin the original example does not make sense), it becomes easier:

dataTypes = $('#' + _target + ' th').map(function(pos, th) {
  return { "sSortDataType": $(th).closest('table').find('td:nth-child('+(pos+1)+')').is(':has(input)') ? 'input' : 'html' };
});
+3
source

Like this:

if (jQuery(this).is(":has(input)")) {

You can simplify your code using .map:

    dataTypes = jQuery('th', $table).map(function () {
        if (jQuery(this).is(":has(input)"))
            return { "sSortDataType": "input" };
        else
            return { "sSortDataType": "html" };
    }).get();
0

, - ?

var thMatches = $('#' + _target + ' th');
var thCount = thMatches.length;
var thCountWithInputs = thMatches.find('input').length;

IDE , , , , .

0
source

Each of them will give you the index of the item in the list. Assuming all of your TH elements belong to a column and you don't have THs elsewhere in the table, you can use this to find the nth-child TD (column) elements of each row and see if any of them contain an input .

jQuery('#' + _target).each(function () {
    var $table = jQuery(this);
    var i = 0;
    jQuery('th', $table).each(function (column) {
        if ($('tbody > tr').find('td:nth-child(' + (column+1) + ')')
                           .has('input')
                           .length) {
            dataTypes[i] = { "sSortDataType": "input" }
        }
        else {
            dataTypes[i] = { "sSortDataType": "html" }
        }

        i++;
    });
});

EDIT : nth-child is unidirectional, while each one is zero based, so I added it to the column variable to take this into account.

0
source

Source: https://habr.com/ru/post/1744926/


All Articles