2016-08-23 85 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

非常感謝,很好的解決方案 –