DEV Community

Gabriel Alejandro López López
Gabriel Alejandro López López

Posted on • Originally published at glpzzz.dev on

1 1

How to toggle attribute values using jQuery

I just came across a very simple question on StackOverflow. In the end is how to toggle the value of an attribute using jQuery.

The long version

This is the explanatory version I created when the author of the question requested for an explanation of my original code. Most of the comments are obvious.

$('thebutton').click(function(){
   var currentRows = $('thetextarea').attr('rows'); //obtain the current number of rows in the textarea
   var newRows; //declare a variable to hold the new number of rows
   if(rows == 1){ //if just one...
       newRows = 5; // it should become 5
   }else{ 
       newRows = 1; //else, (not 1), become 1
   }   
   $('thetextarea').attr('rows', newRows); //assign the new value to the rows attribute of the textarea
});
Enter fullscreen mode Exit fullscreen mode

Short version version

My original answer was...

//short version, the one in the answer
$('thebutton').click(function(){
   $('thetextarea').attr('rows',  $('thetextarea').attr('rows')==1?5:1);
});
Enter fullscreen mode Exit fullscreen mode

I've created a gist for this two versions.

The fancy version (new for me)

I still had the doubt if this could be done easier, and find the next way thanks to this answer:

$('thebutton').click(function(){
   $('thetextarea').attr('rows',  function(index, attr){
       return attr = 1 ? 5 : 1;
   });
});
Enter fullscreen mode Exit fullscreen mode

Just learnt a new thing today. I can sleep easy.

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay