Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

jQuery data-attribute selector doesn't work on click

After click and change data-visible value, I can’t select data-visible with new value.

JS:

$('#imageUploadAction').on('click', function(e) {
 $('#imageUploadAction').html('Close');
 $('.image-upload-action').toggleClass('h-100 show');
 $('#imageUploadAction').attr('data-visible', 'show');
 $('.image-upload-action-btn').removeClass('d-none');
 $('.image-upload-action-btn').addClass('d-block');
});
$('#imageUploadAction[data-visible="show"]').on('click', function(e) {
 console.log('ok');
});

HTML:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<div class="image-upload-action d-flex align-items-center flex-column">
  <a id="imageUploadAction" href="javascript:void(0)" data-visible="hide">edit</a>
  <div class="image-upload-action-btn d-flex justify-content-center align-items-center mt-auto d-block">
    data
  </div>
</div>

How can I fix this problem?

Demo Here

>Solution :

You rather put the value of data-visible in string and check it with a if

$('#imageUploadAction').on('click', function(e) {
  let getStatut = $(this).attr('data-visible');
  
  console.clear();
  console.log(getStatut);
  
  if (getStatut == "hide") {
   $(this).html('Close').attr('data-visible', 'show');
   $(this).parent('.image-upload-action').toggleClass('h-100 show');
   $(this).next('.image-upload-action-btn').removeClass('d-none').addClass('d-block');
  } else {
    // show
   $(this).html('Open').attr('data-visible', 'hide');
   $(this).parent('.image-upload-action').toggleClass('h-100 hide');
   $(this).next('.image-upload-action-btn').removeClass('d-block').addClass('d-none');  
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="image-upload-action d-flex align-items-center flex-column">
  <a id="imageUploadAction" href="javascript:void(0)" data-visible="hide">edit</a>
  <div class="image-upload-action-btn d-flex justify-content-center align-items-center mt-auto d-block">
    data
  </div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading