动态更改输入标签

时间:2019-06-28 04:49:13

标签: jquery html

如何更改通过jQuery动态生成的标签标题

这是我当前的代码

<div class="form-group">
    <label class="col-sm-2 control-label">Scheme Length</label>
    <div class="col-sm-10">
    <input type="number" name="s_Length" min="1" max="24" class="form-control" id="s_Length" placeholder="No. of Draws" required> 
    </div>
</div>`

<div class="dynamiclength"></div>

脚本是

$("#s_Length").change(function(){
    var maxField = $(this).val();
    var wrapper = $('.dynamiclength');
    wrapper.html("");
    var fieldHTML = '<div class="form-group"><label class="col-sm-2 control-label">Draw Dates</label><div class="col-sm-10"><input type="text" name="drawdate[]" class="form-control" placeholder="No. of Draws" value="" required></div>';
    var x;
    for(x=0; x < maxField; x++){ 
        $(wrapper).append(fieldHTML);
    }
});

因此,如何根据编号更改生成的输入字段的标签,例如1st Draw date2nd Draw Date...。生成的字段数量?

1 个答案:

答案 0 :(得分:1)

a)将您的fieldHTML代码放入循环中。

b)创建一个函数以根据数字获取相应的st,nd,rd,th

c)var x;实际上不是必需的。

工作片段:-

$("#s_Length").change(function(){
  var maxField = $(this).val();
  var wrapper = $('.dynamiclength');
  wrapper.html("");
  for(x=0; x < maxField; x++){
    var fieldHTML = '<div class="form-group"><label class="col-sm-2 control-label">'+ordinal_suffix_of(x+1)+ ' Draw Dates</label><div class="col-sm-10"><input type="text" name="drawdate[]" class="form-control" placeholder="No. of Draws" value="" required></div>';
    $(wrapper).append(fieldHTML);
  }
});

function ordinal_suffix_of(i) {
  var j = i % 10,
  k = i % 100;
  if (j == 1 && k != 11) {
    return i + "st";
  }
  if (j == 2 && k != 12) {
    return i + "nd";
  }
  if (j == 3 && k != 13) {
    return i + "rd";
  }
  return i + "th";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
  <label class="col-sm-2 control-label">Scheme Length</label>
  <div class="col-sm-10">
    <input type="number" name="s_Length" min="1" max="24" class="form-control" id="s_Length" placeholder="No. of Draws" required>
  </div>
</div>

<div class="dynamiclength"></div>

参考:-Add st, nd, rd and th (ordinal) suffix to a number