表单提交给出未定义的值

时间:2016-11-05 23:47:51

标签: javascript html

我有一个我正在生成的表,它有一个排序按钮。我想获取用户想要排序的列,但是当我尝试从“byColumn”获取值时,我在sort中得到一个未定义的值: 一些帮助将不胜感激:

tower_0/logits/predictions

enter image description here

2 个答案:

答案 0 :(得分:1)

您需要使用.getElementsByName("byColumn")获取name='byColumn'而不是.getElementById("byColumn")的所有输入。然后遍历所有无线电以获得.checked .value

var data = [{
'TicketNum':'TicketNum',
'Recieved':'Recieved',
'SenderName':'SenderName',
'SenderEmail':'SenderEmail',
'Subject':'Subject',
'Tech':'Tech',
'Status':'Status'
},{
'TicketNum':'TicketNum',
'Recieved':'Recieved',
'SenderName':'SenderName',
'SenderEmail':'SenderEmail',
'Subject':'Subject',
'Tech':'Tech',
'Status':'Status'
},{
'TicketNum':'TicketNum',
'Recieved':'Recieved',
'SenderName':'SenderName',
'SenderEmail':'SenderEmail',
'Subject':'Subject',
'Tech':'Tech',
'Status':'Status'
}];
createTable(data);
    function createTable(data) {
      var str = "<form id='tableSelect' action='javascript:void(0);'><table><thead><tr> <th>TicketNum</th><th>Recieved</th><th>SenderName</th><th>Sender Email</th><th>Subject</th><th>Tech</th><th>Status</th><th>Select</th></tr></thead><tbody>";
    
      for (var key in data) {
        if (!data.hasOwnProperty(key)) continue;
        var row = data[key];
        str += "<tr> <td>";
        str += row['TicketNum'] + "</td><td>";
        str += row['Recieved'] + "</td><td>";
        str += row['SenderName'] + "</td><td>";
        str += row['SenderEmail'] + "</td><td>";
        str += row['Subject'] + "</td><td>";
        str += row['Tech'] + "</td><td>";
        str += row['Status'] + "</td><td>";
        str += "<input type='radio' name ='selectRow' value=" + row['TicketNum'] + ">" + "</td></tr>";
      }
      str += "<tr><td> Sort By: <input type = 'radio' name = 'byColumn' value='TicketNum'><td> Sort By: <input type = 'radio' name = 'byColumn' value='Recieved'><td> Sort By: <input type = 'radio' name = 'byColumn' value='SenderName'><td> Sort By: <input type = 'radio' name = 'byColumn' value='SenderEmail'><td> Sort By: <input type = 'radio' name = 'byColumn' value='Subject'><td> Sort By: <input type = 'radio' name = 'byColumn' value='Tech'><td> Sort By: <input type = 'radio' name = 'byColumn' value='Status'><td> <button type ='button' value='Submit' button class=\"myButton\" onclick=\"sort();\">Sort</button> </tr>";
    
      str += "</tbody></table></form>";
      //console.log(str);
      document.getElementById("table").innerHTML = str;
    }
    
    function sort() {
      //var table = currentTable;
      var col = document.getElementsByName("byColumn"); //the error is on this line
      var sortby;
      for (var i = 0; i < col.length; i++) {
        if (col[i].checked) {
          sortby = col[i].value;
          break;
        }
      }
      alert("sort by: "+sortby);
    
    }
<div id='table'></div>

答案 1 :(得分:0)

您需要将 id =&#34; byColumn&#34; 添加到名为&#34; byColumn&#34;的输入中。

浏览器使用id,服务器使用该名称。

因为您在标记上没有id,所以document.getElementById返回null,null没有value属性。