在append()之后更改输入的值

Changing value of the input after append()

本文关键字:输入 之后 append      更新时间:2023-09-26

我创建了一个模板html块,允许我在单击"添加"按钮时复制该块。这是通过append() 完成的

添加name='category[]'输入字段后,如何更改其值?

例如:

$('#add').click(function() {
   $('#LinesContainer').append($('#templatePlan').html());
   var getCategory = $("#selectCategory").val();
   // How to put getCategory value into category[] field?
});

选择类别并点击+按钮

<div>
  <select id="selectCategory">
      <option value="New">New</option>
      <option value="Old">Old</option>
  </select>
  <input value="+" id="add" type="button"/>
</div>

模板块

<div id="templatePlan" style="display:none;">
 <div style='padding: 5px; border: 1px solid white; background-color: #FFA86F;'>
  <select name="selectType[]"> 
       <option>Consumer</option>
       <option>Business</option>
  </select>
  <input name='category[]' type='hidden' value='' />
 </div>
</div>

<div id="LinesContainer"> </div>

我不确定这是否是一种巧妙的实施方式,还有其他更好的方式吗?

只需选择即可。我建议使用.clone()而不是innerHTML作为模板,这将使选择更容易。否则,您可能有多个类别输入,并且必须使用最后一个。

$('#add').click(function() {
   $('#templatePlan').children('div').clone().appendTo('#LinesContainer')
    .find('input name="category[]"').val($("#selectCategory").val());
});
    //after
     var getCategory = $("#selectCategory").val();
//To set the actual input
    $('input[type="hidden"]').val(getCategory);
//or to update the attribute rather
 $('input[type="hidden"]').attr('name', 'category[' + getCategory + ']');