簡體   English   中英

循環遍歷html表並檢查是否選中了復選框

[英]loop through html table and check if a checkbox is checked or not

我在這里嘗試做的是驗證HTML表。 在繼續之前,我需要至少檢查一個復選框。 它正在做它需要做的事情,除非我沒有選中復選框。

它通過HTML表上的數據計數循環警報“無法找到”。 我怎樣才能讓它變得更好? 我需要在表內循環,以便在選中復選框的同一行上獲取數據。

JS

$('#dataTable').find('tr').each(function () {
    var row = $(this);
    if (row.find('input[type="checkbox"]').is(':checked') ) {
        alert "found"
        //im getting data here.
        });
    }else{
        alert "NOthing found"
    };
});

無需循環任何東西。 只需使用您的選擇器在dataTable中查找已選中的復選框。 如果存在,則滿足您的“真實”條件。

if ($('#dataTable input[type="checkbox"]:checked').size()) {
    // Proceed
}

現在,如果您想對“已檢查”行中的數據執行某些操作,您可以執行以下操作:

var checkedItems = $('#dataTable input[type="checkbox"]:checked').each(function() {
    // Do something with the row
    console.log($(this).parent('tr').find('.data-selector').val());
});
if (!checkedItems.size()) {
    // Nothing was checked
}

Likeso你將為每一個檢查行執行你的代碼,如果沒有檢查行,你將執行你認為合適的,沒有太多資源浪費

  var is_table_empty = true;
 jQuery('#dataTable').find('input[type="checkbox"]:checked').each(function(){
    var row = jQuery(this).closest("tr");
    //do what needs to be done to an active row
    is_table_empty= false;
  });
  if(is_table_empty)
  {
     //do what you need to do if nothing is clicked
  }

嘗試與您的代碼相同。

var checkFound = false;

$('#dataTable').find('tr').each(function() {
  var row = ;
  if (!checkFound && $(this).find('input[type="checkbox"]').is(':checked')) {
    checkFound = true;
    return false;
  }
});

if (checkFound)
  alert('checked Found');
else
  alert('nothig checked');

而不是整個循環中的警報,為什么不使用標志並在找到某些東西時更新它。 根據標志,(在結束 - 循環后)只顯示狀態! 我希望以下修改將幫助您:

var found = false;
$('#dataTable').find('tr').each(function () {   
var row = $(this);
if (row.find('input[type="checkbox"]').is(':checked') ) {
    found=true;
    //alert ("found"); 
    // Do your job here
    }
else{
     //alert "NOthing found"
     //found=false;
    };
});
if (!found){
    alert("Nothing Found");
}
else{
     alert("Found");// Or you can omit the else part
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM