Skip to content Skip to sidebar Skip to footer

False True Change Attr By Onclick JQuery

I need to change data attribute 'aria-selected' by oncklick. But this script does not work. Could you help me, please? SHOW/HIDE&

Solution 1:

The aria-selected is a string... Not a boolean.
So you have to compare it with a string.

<script>
$(document).ready(function($){
  $("a").attr("aria-selected","false");
  $(" ul li a").addClass("accordion");

  $('.accordion').click(function() {
    if ($(this).attr('aria-selected') == "false") {  // Change is here.
      $(this).attr("aria-selected","true");
    } 
    else {
      $(this).attr("aria-selected", "false");
    }
  });
});
</script>

Solution 2:

if ($(this).attr('aria-selected')) {

is supposed to be

if ( !$(this).attr('aria-selected') ) {

You are explicitly setting aria-selected to false on page load. When the element with accordion class is clicked, you seem to toggle the attribute value. But in your case it will always be set to false, cause of your existing if condition.

You can modify the code to make it a bit cleaner

$("a").attr("aria-selected", "false");
$(" ul li a").addClass("accordion");

$('.accordion').click(function(e) {
  e.preventDefault();
  
  var $this = $(this);
  var currentValue = $this.attr('aria-selected');
  
  $this.attr('aria-selected', !(currentValue === 'true'));
});
[aria-selected="true"] {
  color: green;
}

[aria-selected="false"] {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
  <a href="#" aria-selected="true" resource="">SHOW/HIDE</a>
</li>
<li>
  <a href="#" aria-selected="true" resource="">SHOW/HIDE</a>
</li>
<li>
  <a href="#" aria-selected="true" resource="">SHOW/HIDE</a>
</li>
</ul>

Post a Comment for "False True Change Attr By Onclick JQuery"