简体   繁体   English

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

[英]How can I change a part of input's name via jquery?

I have such code in my view: 我认为这样的代码:

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

In my js I'd like to change [1] into [2] or [3] and so on after [quantity] , depending on how many additional forms I create. 在我的js中,我想在[quantity]之后将[1]更改为[2][3] ,依此类推,具体取决于我创建了多少其他表格。 How can I do that? 我怎样才能做到这一点?

This is what I have in my JS: 这就是我的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();
    });

You can do a simple string operation with substr and lastIndexOf to replace the last part of the name. 您可以使用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"> 

  1. Save the clone 保存克隆
  2. Break the name using substring or split and parseInt 使用子字符串或split和parseInt中断名称

Like this 像这样

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM