Why does my media selection script write to ONLY the first input field?

this problem is because of the first “if”, the good text field in only set the first time

to change that, you can add a “data” arguement in HTML and change the JavaScript code like that (look the modification in meta_image_frame.on('select'…)

(function($) {
    'use strict';

    $(function() {

        var meta_image_frame;

        function saveImage(e, uiElement) {

            e.preventDefault();

            if (meta_image_frame) {
                meta_image_frame.field = $("#" + $(e.target).data("field"));

                meta_image_frame.open();
                return;
            }

            meta_image_frame = wp.media.frames.meta_image_frame = wp.media({
                title : "meta_image.title",
                button : {
                    text : "meta_image.button"
                },
                library : {
                    type : 'image'
                }
            });

            meta_image_frame.on('select', function() {
                var media_attachment = meta_image_frame.state()
                        .get('selection').first().toJSON();
                meta_image_frame.field.val(media_attachment.url);
            });

            // Opens the media library frame.
            meta_image_frame.open();

        }

        $('#fa_img1-button').click(function(e) {
            saveImage(e, '#fa_img1');
        });

        $('#fa_img2-button').click(function(e) {
            saveImage(e, '#fa_img2');
        });

    });

})(jQuery);

you can use it with this HTML code :

<input id="fa_img1" type="text" value=""/>
<br/>
<input id="fa_img1-button" type="button" data-field="fa_img1"
    value="Upload Image"/>
<br/>
<br/>

<input id="fa_img2" type="text" value=""/>
<br/>
<input id="fa_img2-button" type="button" data-field="fa_img2"
    value="Upload Image"/>
<br/>
<br/>