jquery - how to append input with name array to a row?

自作多情 提交于 2021-02-11 13:34:33

问题


I'm setting up a form that will dynamically create a text field and append it to the table. The name of the text field is an array, so it contains brackets. The code below doesn't append the input field, rather, it spits back [object HTMLInputElement]. I'm assuming it's because of the brackets? Is there a way to do this?

//HTML
<table id="notesplus" cellpadding="0" cellspacing="0">
<thead></thead>
<tbody></tbody>
</table>

//JQUERY
$(document).ready(function() {
  $('input[id=addIt]').live('click', function() {
     addPlus();
  });
});

function addPlus() {
  var item = document.createElement("textarea");
  item.setAttribute("name", "section[0][aplus]"+mycount+"[notes]");

  var sRow1 = $('<tr>').appendTo('table#notesplus tbody');
  var sCell1 = $('<td>').html(item).appendTo(sRow1);
}

回答1:


At the moment you are trying to using html to insert an HTML object - but jQuery expects to receive an HTML string here and so converts your object to text before appending it to your cell.

Change the last line to:

var sCell1 = $('<td>').append(item).appendTo(sRow1);



回答2:


First of all change your selector $('input[id=addIt]') to $('#addIt'). It much faster.

Also I've checked your code and it works. The only thing is that I've added mycount variable.

Code: http://jsfiddle.net/qha9f/1/




回答3:


I would try doing it like this, see if that works.

function addPlus() {
  var item = document.createElement("textarea");
  var strName = "section[0][aplus]"+mycount+"[notes]";
  item.setAttribute("name", strName);

  $('table#notesplus tbody').append('<tr><td></td></tr>');
  $('table#notesplus tbody tr:last-child td').append(item);      

}

or something along those lines.



来源:https://stackoverflow.com/questions/7705137/jquery-how-to-append-input-with-name-array-to-a-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!