Retrieve .val() from inputs on .focusout()

I have a series of dynamically generated inputs with the same class, eg:

<input class="addressitem" type="text"/>
<input class="addressitem" type="text"/>
<input class="addressitem" type="text"/>

After the user inputs data into each field I want to take that data and place it in the value field of a hidden input.

However, I am having trouble figuring out the best way to do this. So far I've tried:

$(".addressitem").focusout(function() {
    var addressinput = $(this).val();
    console.log(addressinput);
});

and

$(".addressitem").change(function() {
    var addressinput = $(this).val();
    console.log(addressinput);
});

But I cannot get anything to appear in console.

Could anyone point me in the right direction?


Both of your approaches should work as long as you define them inside the document.ready event and you do not have any other script errors in your page.

$(function(){

   $(".addressitem").change(function() {
    var addressinput = $(this).val();
    console.log(addressinput);
   });

   $(".addressitem").focusout(function() {
    var addressinput = $(this).val();
    console.log(addressinput);
   });

});

You may use your browser console to verify the existence of other script errors in the page.

Also remember that, change event occurs on the text input fields when the focus is out. So you will see the console.log when user changes the focus from the textboxes. If you want instant updates, you should consider using keyUp event

Here is a working sample.


EDIT : As per the comment : I had the fields generated by a Jquery click function. I had to move my code within the click function for it to work.

No you don't need to. You can simply use the jQuery on delegation method. When you register an event handler with jQuery on, It will work for current and future elements(dynamically injected) in the DOM.

So your code will be

$(function(){

   $(document).on("change",".addressitem",function() {
     var addressinput = $(this).val();
     console.log(addressinput);
   });     

});