【问题标题】:Dynamically adding HTML form field using jQuery使用 jQuery 动态添加 HTML 表单字段
【发布时间】:2011-08-31 06:07:23
【问题描述】:

由于我不能在表单中使用 div,我想知道如何在不重新加载页面或重写表单的情况下在表单中间添加新字段(我不能在这里使用.append())? (使用 jQuery)

编辑: 这是 HTML:

<form id="form-0" name="0">
<b>what is bla?</b><br>
<input type="radio" name="answerN" value="0"> aaa <br>
<input type="radio" name="answerN" value="1"> bbb <br>
<input type="radio" name="answerN" value="2"> ccc <br>
<input type="radio" name="answerN" value="3"> ddd <br>
//This is where I want to dynamically add the new radio or text line

<input type="submit" value="Submit your answer">
//but HERE is where .append() will put it!

</form>

【问题讨论】:

  • 你的问题没有多大意义。你已经尝试过什么?
  • 我尝试选择表单的倒数第二个子项并使用附加到它,但它不起作用
  • 是什么让你认为不能在form 元素中使用div 元素?

标签: jquery html dom


【解决方案1】:

似乎使这个线程感到困惑的是以下之间的区别:

$('.selector').append("<input type='text'/>"); 

将目标元素附加为 .selector 的子元素。

$("<input type='text' />").appendTo('.selector');

将目标元素附加为 .selector 的子元素。

注意使用不同方法时目标元素和 .selector 的位置如何变化。

你想做的是这样的:

$(function() {

  // append input control at start of form
  $("<input type='text' value='' />")
     .attr("id", "myfieldid")
     .attr("name", "myfieldid")
     .prependTo("#form-0");

  // OR

  // append input control at end of form
  $("<input type='text' value='' />")
     .attr("id", "myfieldid")
     .attr("name", "myfieldid")
     .appendTo("#form-0");

  // OR

  // see .after() or .before() in the api.jquery.com library

});

【讨论】:

    【解决方案2】:

    这将在 ID 为“密码”的输入字段之后插入一个新元素。

    $(document).ready(function(){
      var newInput = $("<input name='new_field' type='text'>");
      $('input#password').after(newInput);
    });
    

    不确定这是否能回答您的问题。

    【讨论】:

      【解决方案3】:

      您可以使用 appendappendTo 等方法添加任何类型的 HTML:

      jQuery manipulation methods

      例子:

      $('form#someform').append('<input type="text" name="something" id="something" />');
      

      【讨论】:

        【解决方案4】:

        类似的东西可能会起作用:

        <script type="text/javascript">
        $(document).ready(function(){
            var $input = $("<input name='myField' type='text'>");
            $('#section2').append($input);
        });
        </script>
        
        <form>
            <div id="section1"><!-- some controls--></div>
            <div id="section2"><!-- for dynamic controls--></div>
        </form>
        

        【讨论】:

        • @Rob, @pixelbobby, tahnx 但问题是如果有一个完整的表格,我不能使用 append 因为它会在 标签下面插入一行,所以它不会成为表单,如何在表单中间插入 $input?
        • @IlyaD - Append 将新元素插入到标签中,在这种情况下,它会将新输入放入表单标签中。
        • @llyaD,请参阅我的更新答案。我添加了将控件插入表单内特定位置的代码。此外,您可以使用prepend()insertAfter()insertBefore() 将控件放置在元素内的特定位置。
        【解决方案5】:

        appendTo 在 Chrome 中使用附加到 FORM 的框架集 ID 似乎存在错误。 直接用div换出属性类型就可以了。

        【讨论】:

          猜你喜欢
          • 2013-09-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-08-05
          • 2012-08-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多