简体   繁体   中英

Javascript inline script onchange not working

i'm having a problem on making my code to adjust to my web server, because of the security purposes, all inline javascript code to my html is not allowed.

everything is already okay i'm just having a hard time converting my other code to pure javascript

Here is my existing code,,,


<label class=qrcode-text-btn><input type=file accept="image/*" capture=environment id="openQRCamera" tabindex=-1></label>

the original code is this

<label class=qrcode-text-btn><input type=file accept="image/*" capture=environment onchange="openQRCamera(this);" tabindex=-1></label> 

the onchange is not working because it is inline in the html.

this function needs to open a camera and detect if there is a qr that exists.

here is what i have now on converting it.

document.querySelector("#openQRCamera").addEventListener('onchange', (node) => {

      var reader = new FileReader();
      reader.onload = function() {
        node.value = "";
        qrcode.callback = function(res) {
         if(res instanceof Error) {
           alert("There is no QR detected");
         } else {
           node.parentNode.previousElementSibling.value = res;
         }
        };
        qrcode.decode(reader.result);
      };
      reader.readAsDataURL(node.files[0]);
});

here is the original code

  function openQRCamera(node) {
    var reader = new FileReader();
    reader.onload = function() {
      node.value = "";
     qrcode.callback = function(res) {
        if(res instanceof Error) {
          alert("There is no QR detected");
        } else {
          node.parentNode.previousElementSibling.value = res;
        }
      };
      qrcode.decode(reader.result);
    };
    reader.readAsDataURL(node.files[0]);
  }

i am using this website as my source of code, everything is working fine in my localhost, but the server is just strict, and i think that's normal for all the websites.

https://www.sitepoint.com/create-qr-code-reader-mobile-website/

i just been stuck and try to do other solution like adding event listener, and append of input just by using jquery, but it's not working. thanks in advance.

The event listener you are using is faulty, instead of listenning to 'onchange' you have to listen to 'change' like so:

document.querySelector("#openQRCamera").addEventListener('change', () => {

//remove the node as parameter and get it with javascript:

var node = document.getElementById('openQRCamera'); ..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM