Alex Zakruzhetskyi
Alex Zakruzhetskyi

Reputation: 1433

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. How can I do that?

This is what I have in my 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();
    });

Upvotes: 3

Views: 259

Answers (2)

mplungjan
mplungjan

Reputation: 178275

  1. Save the clone
  2. Break the name using substring or split and 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();

Upvotes: 2

eisbehr
eisbehr

Reputation: 12452

You can do a simple string operation with substr and lastIndexOf to replace the last part of the name.

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

Upvotes: 3

Related Questions