0

I have added JS to my checkout with jsrequire and I can see my JS file in the developer console.

For testing I tried to console.log the firstname field value on input, like this:

   var name = $("[name='firstname']");


   name.on('input', function(){ console.log(name[0].value);})

It is working in JSfiddle: here.

But it won't work in Magento checkout, I don't get any errors (I do get errors if I write incorrect JS/JQ code).

3
  • Did you check the loading of the input elements and js, normally magento 2 uses knockout js to load checkout fields so its load after page load, so please try to use data binding or render events.if you cant find you can use waiting for content load like js fixes .
    – Lasantha
    Commented Mar 9, 2018 at 9:08
  • @Lasantha I was under the impression that if I use on input it will for sure be called when the fields are already loaded... Commented Mar 9, 2018 at 9:12
  • Try like this $(document).on('EVENT','SELECTOR',function(){ // your code });
    – Lasantha
    Commented Mar 9, 2018 at 9:14

1 Answer 1

0

For some reason, it seems like Magento doesn't like var name = $("[name='firstname']"); selector.

I changed it to: var name = document.getElementsByName("firstname");

And it works.

EDIT Turns out I needed something called delegation, because the fields are generated later and .on won't be applied.

This is the way to do it

$(document).on('click',"input[name='street[0]']",function(){}

(document can be changed for "closer" non changing parent element)

Your Answer

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

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