开发者

Setting up the default value in a new textbox

I am trying to make a form in which there will be a button, when clicking on it a Javascrip开发者_如何学运维t function will be called and a new row with a textbox will be added. In simple words, when clicking on the button, new text will be added. Here is the function:

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);
    }

Now please guide me: how can I set the default value of the text box and drop down box? I mean in this code where should I put <?php echo $data['pno'];?>

I have tried putting in the HTML form; for the first row it works but for the second row it doesn't work. Thanks.


i have solved in this way

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

and on the javascript side

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;


}

might be its not a good solution but for my case it works


How about you save the default value in a separate JS variable in your html like:

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

Or try this:

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

Then when you are adding new input you can use it like this:

el.value = defaultValue;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜