Alex Zakruzhetskyi Alex Zakruzhetskyi - 3 months ago 11
Javascript Question

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

Answer

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