Reputation: 541
I'm trying to take what someone types into one text input and copy it into a second one. I am able to accomplish this, my problem is with the each function. These two input fields (side by side) repeat a couple times in a row and I need to have different values per row. You can see my issue in the fiddle.
Here's some example code:
HTML:
<div class="media">
<div class="row">
<div class="input-holder-one">
<input type="text">
</div>
<div class="input-holder-two">
<input type="text">
</div>
</div>
</div>
<div class="media">
<div class="row">
<div class="input-holder-one">
<input type="text">
</div>
<div class="input-holder-two">
<input type="text">
</div>
</div>
</div>
jQuery
jQuery(function ($) {
$('.media .row').each(function(){
$(this).find('.input-holder-one input').on('keyup', function(){
$('.input-holder-two input').val($('.input-holder-one input').val());
});
});
});
Here's a jsfiddle:
https://jsfiddle.net/p37s6k3c/
Upvotes: 0
Views: 65
Reputation: 2253
It's your selectors that are bad. You need to find the input that is in the same .row
.
jQuery(function ($) {
$(".input-holder-one>input").keyup(function(e){
var $this = $(this);
$this.parents(".row").find(".input-holder-two>input").val($this.val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="media">
<div class="row">
<div class="input-holder-one">
<input type="text">
</div>
<div class="input-holder-two">
<input type="text">
</div>
</div>
</div>
<div class="media">
<div class="row">
<div class="input-holder-one">
<input type="text">
</div>
<div class="input-holder-two">
<input type="text">
</div>
</div>
</div>
Upvotes: 0
Reputation: 21575
The problem here is using just the selector $('.input-holder-two input')
and using .val()
on that will only set the value
of the first element matched (as the selector gets many elements). You can solve this by using $(this).find()
as you did to attach your event handler to get the element you want.
You can use $(this).find(..)
to get those elements in the same way you attached the event handler:
$('.media .row').each(function(){
var $holderOne = $(this).find('.input-holder-one input');
var $holderTwo = $(this).find('.input-holder-two input');
$holderOne.on('keyup', function(){
$holderTwo.val($holderOne.val());
});
});
Upvotes: 2