当表为空时,JavaScript禁用按钮

时间:2015-03-07 11:09:08

标签: javascript jquery html-table

我有一个外部Javascript,我希望在表不为空时启用按钮。

但我似乎无法使其发挥作用。

这是我的代码:

 $(function(){
    var rowCount = $('#uploadsTable tbody tr').length;

    if(rowCount != 0){
        document.getElementById("finalizeButton").disabled = false;
    }
});

3 个答案:

答案 0 :(得分:2)

禁用按钮:

 $('#finalizeButton').attr('disabled','disabled');

所以你的代码将是:

$(function(){
    var rowCount = $('#uploadsTable tbody tr').length;
    if(rowCount < 1){
        $('#finalizeButton').attr('disabled','disabled');
    } else {
        $('#finalizeButton').removeAttr('disabled');
    }
});

答案 1 :(得分:0)

这应该有效。当然,它必须位于按钮下方,或.ready()

$(function(){
    var rowCount = $('#uploadsTable tbody tr').length;

    if(rowCount == 0){
        document.getElementById("finalizeButton").disabled = true;
    }
});

答案 2 :(得分:0)

please check following example:

<!DOCTYPE html>
<html>
<head>
<style>
table, td {
    border: 1px solid black;
}
</style>
</head>
<body>

<p>Click the button to return the number of tr elements in the table.</p>

<table id="myTable">
  <tr>
    <td>cell 1</td>
    <td>cell 2</td>
  </tr>
  <tr>
    <td>cell 3</td>
    <td>cell 4</td>
  </tr>
</table>
<br> 

<button onclick="myFunction()">Try it</button>
<button id = "buy"> Submit</button>

<p id="demo"></p>

<script>
function myFunction() {
    var x = document.getElementById("myTable").rows.length;
   if(x == 0){

      document.getElementById("buy").disabled = true;
    }else{

        document.getElementById("buy").disabled = false;
    }