Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery toggle attribute value

I want to toggle all element attributes with:

$('[contenteditable]').prop('contenteditable', !$(this).prop('contenteditable'));

It does only toggle to true the first time but not to false the second time. What is wrong?

like image 584
daniel Avatar asked Oct 13 '14 12:10

daniel


People also ask

What is toggle () in jQuery?

jQuery toggle() Method The toggle() method toggles between hide() and show() for the selected elements. This method checks the selected elements for visibility. show() is run if an element is hidden.

What are the attributes of toggle selection?

Android Toggle Button can be used to display checked/unchecked (On/Off) state on the button. It is beneficial if user have to change the setting between two states. It can be used to On/Off Sound, Wifi, Bluetooth etc. Since Android 4.0, there is another type of toggle button called switch that provides slider control.

How do I toggle display none and block in jQuery?

In this case, only current container must show and hide. The class container's first div child is initally displayed and the second div child is hidden/ display:none. upon button click, the second div child is displayed, the display:none is change to display:block.


2 Answers

UPDATED FIDDLE

As mentioned : it returns string so workaround is possible using ternary operator: One line solution

$('#contenteditable1').attr('contenteditable',$(this).attr('contenteditable')==='true'?'false':'true' );

Old=>

$('#contenteditable1').click(function()
   {
       if($('#contenteditable1').attr('contenteditable')==='true'){
           //alert("true");
           $('#contenteditable1').attr('contenteditable','false');
       }
       else{
            $('#contenteditable1').attr('contenteditable','true');           
       }
   });   
like image 94
Pratik Avatar answered Sep 17 '22 08:09

Pratik


Use callback function with prop()

$('button').click(function() {
  $('#contenteditable1').prop('contenteditable', function(i, val) {
    return val == "false" ? true : false;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="contenteditable1">hiu</div>
<button>click</button>
like image 27
Pranav C Balan Avatar answered Sep 20 '22 08:09

Pranav C Balan