0
\$\begingroup\$

I am trying to write something that will copy the current <input>s value and enter it into any <input> that start with the same name.

<input> names will follow this pattern: price-0, price-1, price-2, upc-0, upc-1, upc-2.

So if a user enters a value in <input name="price-0"> and hits copy the value should be transferred over to all input whos name start with price

This is the code I've written:

$(document).on('click', '.--copy', function () {
 var input_name = $(this).closest('div').find('input').attr('name').split('-')[0];
 $('input[name^=' + input_name + ']').val($(this).closest('div').find('input').val());
});

A fiddle to make everyones life easier: http://jsfiddle.net/6jGLD/

I feel like there are too many selectors being called upon and the code is somewhat difficult to read.

asked Oct 25, 2013 at 0:29
\$\endgroup\$
1
  • 1
    \$\begingroup\$ It would probably be easier to give each related input an identical class. Other than that, I would do $input = $(this).closest('div').find('input') at the beginning of your function so you don't have to traverse the dom to find the input twice. \$\endgroup\$ Commented Oct 25, 2013 at 0:32

2 Answers 2

2
\$\begingroup\$

One minor improvement I can think of is to create a variable to hold the input element since the element is used twice like

$(document).on('click', '.--copy', function () {
 var $input = $(this).closest('div').find('input'), input_name = $input.attr('name').split('-')[0];
 $('input[name^=' + input_name + ']').val($input.val());
});

Demo: Fiddle

answered Oct 25, 2013 at 0:33
\$\endgroup\$
0
\$\begingroup\$

You can just grab the value of the first input put it in a variable and put that variable as the value of the second input for example

var value = $('input.firstInput').val();
 $('input.secondInput').val(value);

here is a jsfiddle http://jsfiddle.net/suyRd/

answered Oct 25, 2013 at 1:15
\$\endgroup\$
1
  • \$\begingroup\$ The HTML should not be changed in the fiddle \$\endgroup\$ Commented Oct 25, 2013 at 5:38

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.