0

On my text.phtml template I'm trying to add js by requirejs but can't get the php variables to pass through with them coming up as undefined.

Relevant text.phtml

$_option = $block->getOption();
$txtValue = $_option->getNoOfTextbox();

<script type="text/x-magento-init">
{
    "*": {
        "Option_Customoption/js/charCount": {
        "id": "<?= $_option->getId(); ?>",
        "boxCount": "<?= $txtValue; ?>",
        "maxChar": "<?= $_option->getMaxCharacters(); ?>"
        }
    }
}
</script>

charCount.js

define(['jquery'], function($) {
      'use strict';
console.log('#engraving'+config.lineId+'_'+config.id);

      console.log(config.id);
      console.log(config.maxChar);
        console.log(config.boxCount);

function updateCountdown() {


    var count = document.getElementById('#id'+config.lineId+'_'+config.id)
    var remaining = config.maxChar - $(count).val().length;

    document.getElementById('count' + config.lineId + '_' + config.id).innerHTML = remaining;
}

$(document).ready(function($) {
    updateCountdown();
    $(count).change(updateCountdown);
    $(count).keyup(updateCountdown);

});

});

requirejs-config.js

var config = {
  map:  {
    '*': {
      charCount: 'Customoption/js/charCount'
    }
  }
}

Can anyone tell me why the PHP variables aren't passing to the js?

0

Looks like you need to wrap your JS in a return function:

return function (config) {
   ...
}

Try this:

define(['jquery'], function($) {
    'use strict';

    return function (config) {
        console.log('#engraving' + config.lineId + '_' + config.id);

        console.log(config.id);
        console.log(config.maxChar);
        console.log(config.boxCount);

        function updateCountdown() {


            var count = document.getElementById('#id' + config.lineId + '_' + config.id)
            var remaining = config.maxChar - $(count).val().length;

            document.getElementById('count' + config.lineId + '_' + config.id).innerHTML = remaining;
        }

        $(document).ready(function ($) {
            updateCountdown();
            $(count).change(updateCountdown);
            $(count).keyup(updateCountdown);

        });
    }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.