如何通过jquery更改输入名称的一部分?

时间:2016-08-23 11:14:16

标签: javascript jquery ruby-on-rails

我认为我有这样的代码:

<div class="box">
  <input type="text" name="product[size_ids][<%= size.id %>][quantity][1]" readonly class="product_quantity" placeholder="quantity from" value="1">
</div>

在我的js中,我想将[1]更改为[2][3],依此类推[quantity],具体取决于我创建的其他表单数量。我怎样才能做到这一点?

这就是我在JS中所拥有的:

var i = 1

$('.add_another_price_btn').click( function (e) {
    e.preventDefault();
    $(this).prev().clone().insertBefore($(this));
    $(this).prev().find('.remove_another_price_btn').show();
    $(this).prev().find('.product_quantity').removeAttr('readonly');
    $(this).prev().find('.product_quantity').attr('value', '');

    //This is what I tried, but it doesn't work properly. 
    $(this).prev().find('.product_quantity')
    .attr('name', function() { return $(this).attr('name') + '['+ (i++) + ']' }); 

    $('.remove_another_price_btn').click( function (ee) {
      ee.preventDefault();
      $(this).parent().parent().remove();
    });

1 个答案:

答案 0 :(得分:2)

您可以使用substrlastIndexOf执行简单的字符串操作,以替换名称的最后部分。

&#13;
&#13;
// get input and name of input
var input = $("input");
var name = input.attr("name");

// change just the last part
name = name.substr(0, name.lastIndexOf("[")) + "[2]";

// set name back to input
input.attr("name", name);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" name="product[size_ids][<%= size.id %>][quantity][1]" readonly class="product_quantity" placeholder="quantity from" value="1">
&#13;
&#13;
&#13;