Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

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

Posted on • Originally published atglpzzz.dev on

     

How to toggle attribute values using jQuery

I just came across a very simplequestion 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 modeExit 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 modeExit fullscreen mode

I've created agist 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 thisanswer:

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

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

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I’m a software engineer living in Cienfuegos, Cuba. I am a fan of programming, web development, and entrepreneurship. I’m also interested in technology and music.
  • Location
    Cienfuegos, Cuba
  • Education
    Universidad de Cienfuegos
  • Work
    Founder & CEO at Daxslab
  • Joined

More fromGabriel Alejandro López López

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp