0

In the top of my Jquery I've got many variables (associated with values) called : files_1, files_2, etc.

They are created in a script, in the bottom of my page :

<script>
$(function () {
    <?php foreach ($folders as $f) { ?>
    var files_<?=$f['request_id']?> = 0;
    <?php } ?>
    …
});
</script>

In my html I've got a link like :

<a href="#" class="delete" data-request-id="2" title="delete">Delete</a>

data-request-id parameter gives me a number, the ones you've got in my variables names on top. In my example, it's data-request-id="2" : files_2.

Next, I've got a Jquery function that catch data values from links :

$('.request-files').on('click', 'a.delete', function (e) {
    e.preventDefault();
    var $link = $(this);
    var $id = $link.data('request-id');
    console.log(files_$id); // <-- It doesn't work
});

What I need to do is to retrieve the value of the variables files_x. In my example, I tried to get them using files_$id but it doesn't work.

Any idea ?

1 Answer 1

2

If you have your variables defined in the global scrope, they are attached to the window object. So you should be able to access your variables by using bracket notation on the window object:

$('.request-files').on('click', 'a.delete', function (e) {
    e.preventDefault();
    var $link = $(this);
    var $id = $link.data('request-id');
    console.log(window['files_' + $id]); // <-- It DOES work
});

UPD: your variables are in the closure of document.ready function ($(function() {...});), so you won't be able to access them from other scopes. I assume that your click handler is within that closure as well. I can suggest creating a separate object with properties named file_<ID> - it will work much alike as with window:

<script>
$(function () {
    var filesMap = {};
    <?php foreach ($folders as $f) { ?>
    filesMap['files_' + <?=$f['request_id']?>] = 0;
    <?php } ?>
    …
    $('.request-files').on('click', 'a.delete', function (e) {
       e.preventDefault();
       var $link = $(this);
       var $id = $link.data('request-id');
       console.log(filesMap['files_' + $id]); 
    });
});
</script>

I am not familiar with PHP, so the string concatenation in request_id part might be different, but the logic remains.

Sign up to request clarification or add additional context in comments.

1 Comment

I've edited my question because it didn't work for me. Maybe I missed something.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.