在新文本框中设置默认值

时间:2011-03-22 21:53:17

标签: php javascript

我正在尝试创建一个有一个按钮的表单,当点击它时,将调用一个Javascript函数,并添加一个带有文本框的新行。简单来说,单击按钮时,将添加新文本。这是功能:

function addRowToTable()

    {
      var tbl = document.getElementById('tblSample');
      var lastRow = tbl.rows.length;
      // if there's no header row in the table, then iteration = lastRow + 1
      var iteration = lastRow;
      var row = tbl.insertRow(lastRow);

      // left cell
      var cellLeft = row.insertCell(0);
      var textNode = document.createTextNode(iteration);
      cellLeft.appendChild(textNode);

      // right cell
      var cellRight = row.insertCell(1);
      var el = document.createElement('input');
      el.type = 'text';
      el.name = 'txtRow' + iteration;
      el.id = 'txtRow' + iteration;
      el.size = 40;

      cellRight.appendChild(el);

      // select cell
      var cellRightSel = row.insertCell(2);
      var sel = document.createElement('select');
      sel.name = 'selRow' + iteration;
      sel.options[0] = new Option('text zero', 'value0');
      sel.options[1] = new Option('text one', 'value1');
      cellRightSel.appendChild(sel);
    }

现在请指导我:如何设置文本框和下拉框的默认值?我的意思是在这段代码中我应该放置<?php echo $data['pno'];?>

我尝试过输入HTML表单;对于它工作的第一行,但对于第二行它不起作用。感谢。

2 个答案:

答案 0 :(得分:2)

我已经用这种方式解决了

<input type="button" value="Add" onClick="addRowToTable(<?php echo $data['pno'];?>);" />

并在javascript端

function addRowToTable(a)
{
  var tbl = document.getElementById('tblSample');
  var lastRow = tbl.rows.length;
  // if there's no header row in the table, then iteration = lastRow + 1
  var iteration = lastRow;
  var row = tbl.insertRow(lastRow);

  // left cell
  var cellLeft = row.insertCell(0);
  var textNode = document.createTextNode(iteration);
  cellLeft.appendChild(textNode);

  // right cell
  var cellRight = row.insertCell(1);
  var el = document.createElement('input');

  el.type = 'text';
  el.value=a;   // here i have achived the value
  el.name = 'txtRow' + iteration; 
  el.id = 'txtRow' + iteration;
  el.size = 40;


}

可能不是一个好的解决方案,但对于我的情况,它可以工作

答案 1 :(得分:0)

如何将默认值保存在html中的单独JS变量中:

var defaultValue = "<?php echo $data['pno'];?>";

或试试这个:

var defaultValue = "<?= $data['pno'] ?>";

然后,当您添加新的input时,您可以像这样使用它:

el.value = defaultValue;