I've a page with two input fields. I've a JS object (info) containing 'reference' and a 'value' field of each item. For each item, there's a corresponding 'input' field with matched by 'class' attribute. When a user updates a matching input field, I want to add it's 'value' in the info object.
The problem I'm experiencing is that it's putting the value in the last item in the array (location.value
) for either input.
Can anyone help me with where I'm going wrong please? (I could see solutions using 'each' where data for all inputs needs to be added to an array/object. I'm stuck on getting the data for matched fields.)
$(document).ready(function() {
var info = {
name: {
ref: "a2350",
value: ""
},
location: {
ref: "a2351",
value: ""
}
};
for (var p in info) {
if (info.hasOwnProperty(p)) {
$('input.' + p).focusout(function() {
var val = $(this).val();
info[p].value = val; // Only setting value on the last item in array!
//console.log(p); /// p = always location!
out();
})
}
}
function out() {
console.log(info);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="text" class="name" />
<input type="text" class="location" value="" />