I want to add a js function to an input field located in a phtml page
on my magento 2 I have write my function like below:

     function qtyzn() {

and my input is: <input oninput="qtyzn();" value="1" id="nbrbox" />

I dont really get how to make this work on my magento 2


You can use jQuery events like below method will work

require(['jquery', 'jquery/ui'],function($){
      jQuery('#nbrbox').on('input', function(){
           var nbrbox = document.getElementById('nbrbox').value;
           var qtybox = parseFloat(document.getElementById('qtybox').textContent);
           var qtysquare =(Math.round(nbrbox*qtybox*100))/100;

           document.getElementById('qtysquare').innerHTML = qtysquare;
           document.getElementById('qtysquare').value = qtysquare;
           var nbrsqaure = (Math.round(nbrbox*qtybox*100))/100;
           document.getElementById('nbrsqaure').innerHTML = nbrsqaure;
           document.getElementById('nbrsqaure').value = nbrsqaure;
  • where I put this code please! – Nouari zineb May 16 at 12:38
  • 1
    You can put this code in phtml file.....or if you need this code in multiple pages you need to enqueue custom.js and put js code only in that file. Hope you aware of how to enqueue custom.js. – Ranganathan May 16 at 12:42
  • thank you, this what im looking for – Nouari zineb May 16 at 13:10
  • You're welcome... – Ranganathan May 16 at 13:10

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.