I have 2 lists of inputs. One has already loaded values. I want to be able to type something in the other list so it would appear in the first list and replace the already existing value.
<div >
<input type="text" value="a11">
<input type="text" value="a22">
<input type="text" value="a33">
<input type="text" value="">
<input type="text" value="x00123">
<input type="text" value="">
...
(24 inputs total)
</div>
<div >
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
...
(24 inputs total)
</div>
$(".name-calc-col").children().on('input', function(){
var name = [];
for (let x = 1; x <= 24; x ) {
name[x] = $(".name-calc" x).val();
name[x] = name[x] ? name[x] : "";
$(".ingredient" x).val(name[x]);
}
});
When I type something in the .name-calc-col
input its value replaces .ingredient(x)
value as it should, but it also deletes every already existing value (in the primary-list inputs) that were there before (so it won't delete the value that was given from the .name-calc-col
input - when I type something in name-calc1
and name-calc2
, it will replace ingredient1, ingredient2
values as it should and delete ingredient3
a33 value).
I know that the loop takes EVERY value from the .name-calc-col
list (also the empty ones) and replaces the values from the other list.
How can I make it so it won't replace all of the values for the list, but only the one I'm changing?
CodePudding user response:
Using $(this)
to access the current element. This approach explicitly sets the target's class inside input elements:
$(".name-calc-col").children().on('input', function() {
// GET CURRENT INPUT VALUE
const name = $(this).val();
// GET TARGET ELEMENT CLASS
const targetClass = $(this).attr('data-target')
// SET VALUE ON .ingredient TARGET
$("." targetClass).val(name);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<input type="text" value="a11">
<input type="text" value="a22">
<input type="text" value="a33">
</div>
<hr>
<div >
<input type="text" data-target="ingredient1">
<input type="text" data-target="ingredient2">
<input type="text" data-target="ingredient14">
</div>