表格单元格为空时显示警告框

时间:2016-12-31 21:03:02

标签: javascript jquery html html-table

我正在尝试在<td>为空时显示警告框。我的代码如下:

HTML

<table id="results">
  <Full name: <br>
    <input id="userInput" type="text" name="fullname">
    <br>
    <input id="submit" type="submit" value="Submit">
</table>

脚本

var table = $("#results");

// get the sparql variables from the 'head' of the data.
var headerVars = data.head.vars;

// using the vars, make some table headers and add them to the table;
var trHeaders = getTableHeaders(headerVars);
table.append(trHeaders);

// grab the actual results from the data.
var bindings = data.results.bindings;

// for each result, make a table row and add it to the table.
for (rowIdx in bindings) {
  table.append(getTableRow(headerVars, bindings[rowIdx]));
}

function getTableRow(headerVars, rowData) {
  var tr = $("<tr></tr>");

  for (var i in headerVars) {
    tr.append(getTableCell(headerVars[i], rowData));
  }

  return tr;
}

function getTableCell(fieldName, rowData) {

                    var td = $("<td></td>");
                    var fieldData = rowData[fieldName];

                    if ($('td').html().trim() == "") {
                        alert("td is empty");
                    }
                    else {
                        alert("fieldName = [" + fieldName + "] rowData[fieldName][value] = [" + rowData[fieldName]["value"] + "]");
                        td.html(fieldData["value"]);
                        return td;
                    }
                    console.log(td);


                }

function getTableHeaders(headerVars) {
  var trHeaders = $("<tr></tr>");
  for (var i in headerVars) {
    trHeaders.append($("<th>" + headerVars[i] + "</th>"));
  }
  return trHeaders;
}

现在警报框没有弹出,那么当<td>提交的文件为空时如何显示警告框?

1 个答案:

答案 0 :(得分:0)

当我们执行$("<td></td>")时,jQuery会创建一个td元素并返回它,因此您的条件td == 0将始终为false,因此您看不到警报。

要在html页面上选择一个td,我们需要使用$('td'),并检查该元素是空的,使用jQuery的.html()函数。

因此,像

if($('td').html().trim() === ''){
   alert('td is empty')
}

希望这有帮助。

在你的情况下试试这个:

function getTableCell(fieldName, rowData) {
  var td = $("<td></td>");
  var fieldData = rowData[fieldName];
  alert("fieldName = [" + fieldName + "] rowData[fieldName][value] = [" + rowData[fieldName]["value"] + "]");

  //You need to check id fieldData["value"] is empty and then trigger alert, as if this empty your td will be empty
  if (fieldData["value"] && fieldData["value"].trim().length !== 0) {
    td.html(fieldData["value"]);
    return td;
  } else {
    alert("td is empty");
  }
  console.log(td);
}