Home > Back-end >  Why I am getting Undefined Value when I click on image ? How to fix this?
Why I am getting Undefined Value when I click on image ? How to fix this?

Time:04-23

I am getting this error (undefined) when I am clicking on image to get the value of image. Can you please explain the reason behind it and how to get and pass the value to onclick function in this case.

      <div id="fi" value="0">
        <img src="first.JPG" alt="first" id="first" value="01" onclick="checkingg(this.value)"/>
      </div>

      // inside script tag
      function checking(img_val) {
        console.log(img_val);
      }

CodePudding user response:

No problem in your approach, except value is not a valid attribute on image and hence will be undefined. Use custom data attributes data-*:

      function checking(img_val) {
        console.log(img_val);
      }
  <div id="fi" value="0">
        <img src="https://media.istockphoto.com/photos/analyzing-samples-in-test-tube-backgrounds-picture-id1290116527?b=1&k=20&m=1290116527&s=170667a&w=0&h=51bfejWaiLIK8ZeeP7u7q0b1UINUwx3dbH86HZNNuPA=" alt="first" id="first" data-value="01" onclick="checking(this.dataset.value)"/>
      </div>

  • Related