Reputation: 3659
I have and two array inputs. I want them to be equal on key up event. The problem is I cannot get each 1st input value to be equal on each 2nd input.
JSFIDDLE (This fiddle only copies the first input)
Jquery I have used. (
Which only works for mgr[1] to gm[1]. but fails to copy mgr[2] to gm[2] or mgr3 to gm3
$(document).ready(function() { $("#mgr").keyup(function(){ $('#gm').val($('#mgr').val()); });
});
I have also tried this jquery. But its copies 1st input value to all 2nd input SEE FIDDLE
$(document).ready(function() {
$('input[name="mgr[]"]').keyup(function(){
var val = 0;
$('input[name="mgr[]"]').each(function() {
val += Number($(this).val());
});
$('input[name="gm[]"]').each(function() {
$(this).val(val);
});
});
});
What I want
Upvotes: 0
Views: 157
Reputation: 2854
As per your HTML structure this code will help you.
$(document).ready(function() {
$("input[type=text]").on("input", function() {
if($(this).index() / 2 != 0 || $(this).index() == 0) {
$(this).next().val($(this).val());
}
});
});
Upvotes: 1
Reputation: 15982
First and foremost you should stop using the same ID's in html, FOREVER. Your code will never work the way it's supposed to, you're going against convention.
I've managed to correct your code to work in an array like manner, where the 2nd input is found through the 1st input's index.
http://jsfiddle.net/guanzo/YBQKz/8/
$('input[name="mgr[]"]').keyup(function(){
var index = $(this).index('input[name="mgr[]"]')
$('input[name="gm[]"]').eq(index).val($(this).val());
});
Upvotes: 1
Reputation: 426
First short explication about the code that you are follow. In Jquery you have selectors for get the elements in the DOM, those selectors can be "." for class or "#", for id attribute.
So in the example the jquery function is saying if you click on a element with "js-key-up" class take the value in id attribute and then search an element with the id atribute with this form '#' + id + '-in-document'.
In your case can be something like this code.
<input class="mgr" id="1">
<input class="mgr" id="2">
<input class="mgr" id="3">
<input id="gm1">
<input id="gm2">
<input id="gm3">
$('.mgr').keyup(function (e) {
var id = $(this).attr('id');
$('#gm' + id').html($(this).val());
});
I hope it helps. Good luck!
Upvotes: 0