2016-08-23 49 views
2

我有这样的代码在我看来:如何通过jquery更改部分输入的名称?

<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(); 
    }); 
+0

定期EXPR激情 – epascarello

+0

@VijayMaheriya他做到了。 – mplungjan

回答

2

你可以做一个简单的字符串操作与substrlastIndexOf更换名称的最后一部分。

// 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);
<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">

2
  1. 保存克隆
  2. 使用子或分裂,parseInt函数打破名称

像这样

var $clone = $(this).prev().clone(), 
    $prodQ = $clone.find('.product_quantity'), 
    name = $prodQ.attr("name"), 
    parts = name.split("quantity]["), 
    newName = parts[0]+"quantity][", 
    num = parseInt(parts[1],10); // or a counter 
num++; 
newName += num+"]"; 
$prodQ.removeAttr('readonly').attr('value', '').attr('name',newName); 
$clone.insertBefore($(this)); 
$clone.find('.remove_another_price_btn').show(); 
+0

我的IDE告诉我,这个部分弄错了:'(parseInt(parts [1],10)' –

+0

请参阅更新 – mplungjan

+0

非常感谢,很好的解决方案 –